gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:58:21 24 4
gpt4 key购买 nike

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

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

最佳答案

2018 年 1 月 22 日更新:

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

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

如果操作的目的是获取数据,React 将来可能会支持这些事情的新策略。与此同时,坚持使用提到的两个生命周期 Hook 是安全的。

关于reactjs - 我应该在 componentWillReceiveProps 中调用操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38575792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com