javascript - 执行 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()
action 方法获取了一些项目并更新了uncat_items
redux 存储中的值(我可以在渲染/其他方法中看到变量的预期值,没有this.props.uncat_items
任何问题)。但是,对于这种特殊情况,我需要做的是在fetchItems
执行该方法并更新uncat_items
商店中的 之后,我需要调用setState
并categorized_items
使用uncat_items
. this.setState
我知道在方法中这样调用componentDidMount
是不正确的,但我不知道该怎么做。如您所见,我尝试 print out this.props.uncat_items
,但它返回一个空数组,即使它执行了 action 方法并在 reducer 中正确更新。有人可以给我一个想法如何以正确的方式做吗?基本上,之后componentDidMount
执行时,使用更新后的 redux 存储中的特定变量设置状态。
解决方案
您的代码中的问题是您调用了一个异步操作 ( this.props.fetchItems()
),然后立即调用this.setState()
- 这发生在fetchItems
请求完成之前(因此,在props.uncat_items
填充之前)。
假设您使用的是最新的 React,根据您的特定用例,您可以:
1)丢弃状态,直接this.props.uncat_items
在渲染函数中使用。
2)static getDerivedStateFromProps
由于新的道具而用于更新状态。
然而,正如文档中提到的,它并不是真正推荐的,因为大多数情况可以以不同的方式处理(例如,通过切换到受控组件,如解决方案 #1 中所述)。可以在本文中找到更长的描述,文档中也提到了该描述。
推荐阅读
- java - 如何在 Mapbox Android 上添加多个图层?
- android - 如何在 OSM(打开地图街道)的 Android Studio 中绘制一条线(Polyline)?
- python - 在遗传算法中选择父母
- excel - 如何在 Excel 中计算“-”
- python - 带有 python 的 debhelper 不部署命名空间包
- sql-server - 全文搜索星号返回错误结果
- excel - 如何根据两个总和中的较大者设置单元格的值?
- python - 如果主机在 5 秒内没有响应,如何关闭连接
- kubernetes - 究竟何时将 ownerReference 的控制器字段设置为 true?
- angular - 如何在 Angular 6 中使用锚链接而不刷新页面?