【发布时间】:2016-11-29 06:29:07
【问题描述】:
我的直觉告诉我没有,但我很难想出更好的方法。
目前,我有一个显示项目列表的组件。根据提供的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)
})
}
这一切都很好,但是现在我的要求已经改变,我需要添加一个新的过滤器。对于新过滤器,我必须执行 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)
})
}
【问题讨论】:
-
如果您只想执行一次 API 调用,请在 componentWillMount() 中执行,否则在 componentDidMount() 中执行
-
很遗憾,每次更新
this.props. otherFilter时都必须执行API调用。