我应该在 componentWillReceiveProps 中调用操作吗?

Should I call actions within componentWillReceiveProps?

我的直觉告诉我不会,但我很难想到更好的方法。

目前,我有一个显示项目列表的组件。根据提供的 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)
        })
}

一切都很好,但现在我的要求发生了变化,我需要添加一个新的过滤器。对于新过滤器,我必须对 return 有效项目 ID 列表执行 API 调用,我只想在同一列表组件中显示具有这些 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 日更新:

最近有一个 RFC-PR for React was merged,它弃用了 componentWillReceiveProps,因为它在即将到来的异步渲染模式中使用时可能会被取消保存。一个例子就是从这个生命周期挂钩调用通量操作。

调用动作的正确位置(即 side effects)是在 React 完成渲染之后,因此这意味着 componentDidMountcomponentDidUpdate

如果动作的目的是获取数据,React 可能会在未来支持针对这些事情的新策略。同时坚持使用上面提到的两个生命周期钩子是安全的。