javascript - React 状态被“损坏”
问题描述
我正在开发一个简单的 React.JS 前端。
我基本上有一个历史数据的浏览 SPA。该设计有一堆过滤器,我需要一次填充一个,从我的逻辑层次结构中的顶部开始。
我做类似的事情:
componentWillMount() {
if (!this.props.advertisers) {
this.props.loadAdvertisers();
}
}
加载广告客户数组后,我将其映射到选择组件的选项(使用react-select
),将选择设置为列表中的第一项并加载下一个列表 - campaigns
。
据我了解,最好的方法仍然是componentWillReceiveProps()
,我有点困惑如何以不同的方式完成,因为它componentWillReceiveProps
正在被逐步淘汰。
我的代码如下所示:
componentWillReceiveProps(nextProps) {
if (nextProps.advertisers && !this.props.advertisers) {
const advertiser = nextProps.advertisers[0];
this.setState({
advertiser: {
value: advertiser['id'],
label: advertiser['name']
}
});
nextProps.loadCampaigns(advertiser['id']);
}
// if campaigns list changed, reload the next filtered array
if (nextProps.campaigns && this.props.campaigns !== nextProps.campaigns) {
...
}
这很好,直到我决定添加一个加载指示器。我映射了状态的loading
属性,例如campaigns
它通过this.props.campaignsLoading
然后做:
return (this.props.campaignsLoading || this.props...Loading || ...) ?
<ProgressIndicator> : <MainContentPanel>
现在的问题是,我的状态在内部没有正确设置componentWillReceiveProps()
。
该项目正在使用@rematch
,我最初用@rematch/loading
插件尝试过这个,当问题发生时,认为插件做错了,不知何故。然后,我手动映射loading
了属性,只是又加了两个dispatch
es来手动设置loading flag
。
所有道具都被正确设置/取消设置,但我的状态没有被设置,没有任何效果。有什么建议么?
解决方案
当你这样做
if (nextProps.advertisers && !this.props.advertisers) {
您不是在比较下一个和上一个道具。“this.props.advertisers”可能已经设置好了,所以你永远不会进入 setState 行。虽然使用 componentWillReceiveProps 不再是推荐的方式(你可能不需要派生状态),但你可能想要大致做的是:
if (nextProps.advertisers && nextProps.advertisers !== !this.props.advertisers) {
推荐阅读
- r - 为什么调用函数时会出错,而单步执行时却没有?
- python - python - 根据正则表达式模式获取精确的字符串
- python - ssd mobilenet v1:更改特征图布局
- tcp - 如何在 Jmeter 的 TCP 采样器中设置行尾字节值
- dataframe - 如何分组并获取 Spark Dataframe 中的中位数
- hibernate - 自动计算休眠实体中的字段
- firebase - 在删除应用程序并重新安装之前,React Native Firebase 不起作用
- php - Symfony Validator - 在散列之前检查密码长度和内容
- javascript - 等待对机器人消息的反应
- css - 在图像下方移动轮播指示器