[英]React state gets "corrupted"
我正在研究一个简单的 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
属性,例如,对于它通过this.props.campaignsLoading
公开的campaigns
,然后执行:
return (this.props.campaignsLoading || this.props...Loading || ...) ?
<ProgressIndicator> : <MainContentPanel>
现在的问题是,我的状态没有在componentWillReceiveProps()
中正确设置。
该项目正在使用@rematch
,我最初尝试使用@rematch/loading
插件进行此操作,当问题发生时,我认为插件以某种方式做错了。 然后,我手动映射loading
属性,并添加了两个dispatch
es来手动设置加载flag
。
所有的道具都被正确设置/取消设置,但我的状态没有被设置并且没有任何效果。 有什么建议么?
当你做
if (nextProps.advertisers && !this.props.advertisers) {
您不是在比较下一个和上一个道具。 “this.props.advertisers”可能已经设置好,因此您永远不会进入 setState 行。 虽然使用 componentWillReceiveProps 不再是推荐的方法( 你可能不需要派生状态),但你可能想要做的大致是:
if (nextProps.advertisers && nextProps.advertisers !== !this.props.advertisers) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.