【发布时间】:2021-07-21 23:55:02
【问题描述】:
我正在关注this Udemy course,它正在开发一款按需订餐应用程序。到目前为止,我很喜欢这门课程,除了讲师在整个课程中做出了一些有问题的决定;无数其他人以及 10 多年的行业经验教我从未做的事情。
其中一个例子是他复制了一个 React Native Paper Searchbar 组件,用于两个单独的 React Navigation 屏幕。这违反了我认为是编程中最重要的设计原则之一的 DRY 原则。
他对这种重复的理由是,与另一个相比,他在组件的一个实例中进行了一些细微的样式更改。但恕我直言,这些差异可以用更优雅的方式处理。
这是我目前得到的:
// search.component.js
import React, { useContext, useEffect, useState } from 'react';
import styled from 'styled-components/native';
import { Searchbar } from 'react-native-paper';
import { LocationContext } from '../../services/location/location.context';
const SearchBar = () => {
const { searchQuery, location, error, setError, searchLocations } = useContext(LocationContext);
const [lastSearch, setLastSearch] = useState('San Francisco');
const [currentSearch, setCurrentSearch] = useState(searchQuery);
// As an aside, I'd like to know if there's a better way to do this too!
useEffect(() => {
!error && setLastSearch(currentSearch);
}, [location]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<Searchbar
placeholder="Search for a location..."
value={error ? lastSearch : currentSearch}
onChangeText={newSearch => {
setCurrentSearch(newSearch);
setError(null);
}}
onSubmitEditing={() => searchLocations(currentSearch)}
/>
);
};
// restaurant.search.component.js
const RestaurantSearchContainer = styled.View`
padding: ${props => props.theme.spacing.md};
`;
export const RestaurantSearch = () => (
<RestaurantSearchContainer>
<Search />
</RestaurantSearchContainer>
);
// map.search.component.js
const MapSearchContainer = styled.View`
padding: ${props => props.theme.space[3]};
position: absolute;
top: ${props => props.theme.space[4]};
width: 100%;
z-index: 1;
`;
export const MapSearch = () => (
<MapSearchContainer>
<SearchBar />
</MapSearchContainer>
);
LocationContext 除了从 JSON 文件加载一些模拟位置数据外,并没有做太多的 ATM 工作,但它最终会使用 Google Places API 来提供特定区域的餐馆数据。 RestaurantSearch 是Restaurants 屏幕上的搜索栏,而MapSearch 是完全相同 的组件,但在Map 屏幕上,因此样式有点不同,如您所见。
恕我直言,使用这种继承模式可以使代码更清晰、更易于维护——这就是 DRY 原则的全部目的以及它如此重要的原因。但是我不知道当用户在Restaurants 屏幕上搜索时如何告诉 React 重新渲染地图,反之亦然。
任何与此相关的指导,包括关于如何进一步改进代码的提示,将不胜感激:-)
【问题讨论】:
标签: javascript reactjs react-native react-navigation react-native-paper