gpt4 book ai didi

javascript - componentWillReceiveProps 包含多个 if

转载 作者:行者123 更新时间:2023-12-03 02:21:38 26 4
gpt4 key购买 nike

我对 React 开发还很陌生,但我已经使用 React+Redux 开发了 3 个大项目,并且我看到了一个我非常不喜欢的模式:

componentWillReceiveProps(nextProps) {
if (nextProps.params.type === TYPE_NEW_USER) {
this.modalUsername = this.props.showPopup( < NewUsernamePopup onClose = {::this.closeUsernamePopup
}
/>, USERNAME_POPUP_ID, true);
}
if (this.state.kind !== nextProps.kind || this.state.filter !== nextProps.filter || this.state.hashtags !== nextProps.hashtags) {
this.setState({
results: [],
loading: true,
kind: nextProps.kind,
filter: nextProps.filter,
hashtags: nextProps.hashtags
}, () => this.manageResults(nextProps.results, false));
} else {
this.manageResults(nextProps.results, true);
}
this.managePages(nextProps.paging);
}

我想避免在 componentWillReceiveProps 中使用 if。你如何处理?我们分析了另一个使用 Flux 和回调注册的项目。它看起来像:

componentWillMount() { 
EntityStore.on(EntityActions.ENTITIES_LOADED, this.getData.bind(this));
EntityActions.entitiesLoaded();
}

第一个事件由组件发出,但随后存储发出事件并且组件更新。此外,单个存储会保留其状态,并且如果已经拥有内容,则不会重复异步调用。我个人喜欢避免 ifs,但我不想失去 Redux(它的社区和工具)。

如何在组件外部的 componentWillReceiveProps 内添加当前逻辑 (ifs)?我想在服务层中处理逻辑,而不是在组件内部。

我非常乐意阅读您对此的看法,因为我一直在努力寻找合适的解决方案。

最佳答案

redux 方法是将逻辑放入 actions/reducer 中。

所以我不知道你的 manageResults 方法是做什么的,但它可能是你想要移动到 reducer 中的逻辑部分,这样你就不需要再从你的组件中调用它.

因此,kindfilterhashtags 变量应该仅从 redux 操作中更新。

关于javascript - componentWillReceiveProps 包含多个 if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49134105/

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