【问题标题】:Should I call actions within componentWillReceiveProps?我应该在 componentWillReceiveProps 中调用操作吗?
【发布时间】: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调用。

标签: reactjs flux


【解决方案1】:

2018 年 1 月 22 日更新:

最近一个RFC-PR for React was merged,它弃用了componentWillReceiveProps,因为它在即将到来的异步渲染模式下使用时可能无法保存。这方面的一个示例可以是从此生命周期挂钩中调用通量操作。

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

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

【讨论】:

  • 嗯...看来这确实是最好的方法。谢谢。
猜你喜欢
  • 2016-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-22
  • 1970-01-01
  • 2010-09-22
  • 2011-10-22
  • 1970-01-01
相关资源
最近更新 更多