我有以下state
变量和componentDidMount
我的组件上的方法:
state = {
categorized_items: []
}
componentDidMount() {
this.props.fetchItems()
// I'm trying to do the following
console.log('uncat_items: ', this.props.uncat_items)
this.setState({categorized_items: this.props.uncat_items})
}
render () {....}
function mapStateToProps({ items_reducer }) {
return {
uncat_items: items_reducer.uncat_items
}
}
this.props.fetchItems()
操作方法获取多个项目并更新 uncat_items
在 redux 存储中就好了(我可以在渲染/其他方法中看到 this.props.uncat_items
变量的预期值,没有任何问题)。但是,我需要针对此特殊情况执行的操作是在 fetchItems
之后。方法被执行并更新 uncat_items
在商店,我需要调用setState
并更新categorized_items
处于 uncat_items
的状态。我知道打电话this.setState
就像这样componentDidMount
方法不正确,但我不知道该怎么做。正如你所看到的,我尝试打印出 this.props.uncat_items
,但它返回一个空数组,即使它执行了操作方法并在 reducer 中正确更新。有人可以告诉我如何以正确的方式做到这一点吗?基本上,在componentDidMount
之后执行时,使用更新后的 redux 存储中的特定变量设置状态。
最佳答案
代码中的问题是您调用异步操作 (this.props.fetchItems()
),然后立即调用 this.setState()
- 这种情况会发生在 fetchItems
请求完成之前(即在 props.uncat_items
填充之前)。
假设您使用的是最新的 React,根据您的特定用例,您可以:
1) 删除状态并直接在渲染函数中使用 this.props.uncat_items
。
2) 使用static getDerivedStateFromProps
更新由于新 Prop 而产生的状态。
但是,如 the docs 中所述,实际上并不建议这样做,因为大多数情况都可以以不同的方式处理(例如,通过切换到受控组件,如解决方案 #1 中所述)。更长的描述可以在 this article 中找到。 ,文档中也提到了。
关于javascript - 执行componentDidMount后无法设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52881860/