【发布时间】:2017-01-24 20:22:54
【问题描述】:
我正在尝试了解如何构建具有不同“页面”或“视图”的 ReactJS 应用程序。
我有以下组件作为我的基础应用程序,我正在使用 React 状态下的 currentState 属性来切换视图中哪些组件处于活动状态。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {currentState: 'Loading', recipes: []};
this.appStates = {
'Loading': <Loading/>,
'Home': <RecipeList recipes={this.state.recipes}/>
}
}
dataLoaded(data) {
this.setState({
recipes: data,
currentState: 'Home'
});
}
componentDidMount() {
// AJAX Code that retrieves recipes from server and then calls dataLoaded
}
render() {
return this.appStates[this.state.currentState];
}
}
哪个工作,但是当触发 dataLoaded 回调时,组件永远不会收到更新的食谱数组。
我怎样才能根据应用中的更新状态来更新它的道具?
还是我以错误的方式处理整个事情?
【问题讨论】:
-
我假设正在发生的事情是因为“Home”组件是在构造函数中定义的,并且您将其食谱设置为那里的数组,当您更新食谱数组时,您不是将元素推送到现有数组上,而是为变量设置一个新数组,因此组件永远不会使用新数据更新。
标签: reactjs