我的直觉告诉我没有,但我很难想到一个更好的方法.
目前,我有一个显示项目列表的组件.根据提供的内容props,此列表可能会更改(即过滤更改或上下文更改)
例如,给定一个新的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)
})
}
Run Code Online (Sandbox Code Playgroud)
这一切都很好,但现在我的要求已经改变,我需要添加一个新的过滤器.对于新过滤器,我必须执行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)
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3812 次 |
| 最近记录: |