[英]Unable to set state after executing componentDidMount
我的componentDidMount
上具有以下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()
操作方法可获取许多项并更新redux存储中的uncat_items
很好(我可以在render / other方法中看到this.props.uncat_items
变量的this.props.uncat_items
,没有任何问题) 。 不过,以后有什么需要我为这个特殊的情况下做的是正确的fetchItems
执行方法,它更新uncat_items
在店里,我需要调用setState
和更新categorized_items
的状态uncat_items
。 我知道在componentDidMount
方法中像这样调用this.setState
是不正确的,但是我不知道该怎么做。 如您所见,我尝试打印出this.props.uncat_items
,但这返回了一个空数组,即使它执行了action方法并在reducer中正确更新了。 有人可以给我一个正确的方法吗? 基本上,执行componentDidMount
之后,使用来自更新后的redux存储区的特定变量设置状态。
代码中的问题是,您先调用一个异步操作( this.props.fetchItems()
),然后立即调用this.setState()
,此操作发生在fetchItems
请求完成之前(因此,在填充props.uncat_items
之前)。
假设您使用的是最新的React,根据您的特定用例,您可以:
1)放置状态,仅在render函数中直接使用this.props.uncat_items
。
2)由于新的道具,使用static getDerivedStateFromProps
来更新状态。
但是 ,正如在文档中提到的那样,实际上并不建议这样做,因为大多数情况下可以用不同的方式处理(例如,如解决方案1所述,通过切换到受控组件)。 可以在本文中找到更长的描述,在文档中也有提及。
您可以使用componentDidUpdate生命周期方法。 看起来好像在安装组件时,商店可能仍包含该状态的默认值。 然后,它会像您提到的那样在redux存储中正确更新,但组件状态不会更新。
在组件收到新的道具后更新组件状态:
componentDidUpdate(prevProps){
// compare prevProps to current props and update
if(this.props.uncat_items !== prevProps.uncat_items) {
this.setState({categorized_items: this.props.uncat_items})
}
}
如评论中所述,直接在渲染方法中使用props是更理想的解决方案,因为您不希望不必要地重新渲染组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.