我的直觉告诉我没有,但是我一直在想更好的方法。
当前,我有一个显示项目列表的组件。根据提供的内容props
,此列表可能会更改(即过滤更改或上下文更改)
例如,给定new this.props.type
,状态将更新如下:
componentWillReceiveProps(nextProps) {
if (nextProps.type == this.state.filters.type) return
this.setState({
filters: {
...this.state.filters,
type: nextProps.type,
},
items: ItemsStore.getItems().filter(item => item.type == nextProps.type)
})
}
一切都很好,但是现在我的要求已经改变,我需要添加一个新的过滤器。对于新的过滤器,我必须执行API调用以返回有效项目ID的列表,并且我只想在同一列表组件中显示具有这些ID的项目。我应该怎么做呢?
我曾考虑过从中调用适当的操作componentWillReceiveProps
,但这似乎并不正确。
componentWillReceiveProps(nextProps) {
if (nextProps.type == this.state.filters.type && nextProps.otherFilter == this.state.filters.otherFilter) return
if (nextProps.otherFilter != this.state.filters.otherFilter) {
ItemsActions.getValidIdsForOtherFilter(nextProps.otherFilter)
// items will be properly updated in store change listener, onStoreChange below
}
this.setState({
filters: {
...this.state.filters,
type: nextProps.type,
otherFilter: nextProps.otherFilter,
},
items: ItemsStore.getItems().filter(item => item.type == nextProps.type)
})
},
onStoreChange() {
let validIds = ItemsStore.getValidIds()
this.setState({
items: ItemsStore.getItems().filter(item => item.type == this.state.filters.type && validIds.indexOf(item.id) > -1)
})
}
2018年1月22日更新:
最近,React的RFC-PR被合并了,因为componentWillReceiveProps
在即将到来的异步渲染模式中使用它时可能无法保存,因此不推荐使用。例如,可以从此生命周期挂钩调用流量动作。
调用动作(即副作用)的正确位置是在React完成渲染之后,因此意味着componentDidMount
或componentDidUpdate
。
如果该动作的目的是获取数据,那么React将来可能会支持针对这些事情的新策略。同时,坚持使用上述两个生命周期挂钩是安全的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句