我在尝试了解如何使用不同的“页面”或“视图”构建ReactJS应用程序。在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回调被触发时,组件从不接收更新的配方数组。
如何根据应用程序中更新的状态更新其道具?
或者我以错误的方式接近这件事?
我认为正在发生的事情是因为“家”组件在构造函数中被定义,并且您将它的配方设置到数组中,当您更新配方数组时,您不会将元素推送到现有数组上,而是将新数组设置为该变量,因此组件从不更新为新数据。 – dule