有几个解决方案可以解决您的问题,而无需实际使用状态管理库,
第一:提升国家地位,
这是最正确的解决方案,因为您的组件和路由不是高度嵌套的,并且数据需要由彼此兄弟的组件处理,
class Root extends React.Component {
state = {
restaurant: [] // store the restaurant data here instead of MyFoodApp
}
restaurantUpdater = () => {
//utility function to update state
}
render() {
return (
<Router>
<div className="router">
<Switch>
<Route exact path="/" render={props => <MyFoodApp {...props} restaurant={this.state.data} restaurantUpdater={this.restaurantUpdater} />} />
<Route
path="/restaurant/:slug"
render={props => <RestaurantPage {...props} restaurant={this.state.data} restaurantUpdater={this.restaurantUpdater} />}
/>
<Route render={(props) => <NotFound {...props}/>} />
</Switch>
</div>
</Router>
);
}
}
第二:使用Context API
您可以利用Context
当您的数据需要向下传递到不同级别的组件时。正如反应文档所说
不要仅仅为了避免将 props 向下传递几个级别而使用上下文。戳
需要在多个组件中访问相同数据的情况
在多个层面上。
您可以使用以下方式配置上下文的使用React 16.3 context API https://reactjs.org/docs/context.html#dynamic-context like
export const RestaurantContext = React.createContext({
restaurant: [],
restaurantUpdater: () => {},
});
class RestaurantProvider extends React.Component {
state = {
restaurant: [] // store the restaurant data here instead of MyFoodApp
}
restaurantUpdater = () => {
//utility function to update state
}
render() {
<RestaurantContext.Provider value={this.state}>
{this.props.children}
</RestaurantContext.Provider>
}
}
然后为消费者创建一个 HOC
import RestaurantContext from 'path/to/restaurantContext'
const withContext = (Component) => {
return (props) => <RestaurantContext.Consumer>
{(restaurant, restaurantUpdater) => <Component {...props} restaurant={restaurant} restaurantUpdater={restaurantUpdater} />}
</RestaurantContext.Consumer>
}
现在您可以在组件中使用它,例如
export default withContext(MyFoodApp);
你的 FoodApp 可以使用restaurant
and restaurantUpdater
来自像这样的道具
const { restaurant, restaurantUpdater} = this.props
同样,您可以在其他组件中使用它