javascript - componentWillReceiveProps 包含多个 if

标签 javascript reactjs redux react-redux

我对 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/

相关文章:

javascript - 如何在加载某个特定变量后仅在 React 中触发一次 useEffect

reactjs - 不变违规 : Could not find "store" in either the context or props of "Connect(App)"

javascript - 我如何使用 JSDoc 记录一个对象?

javascript - 指定用逗号分隔时哪个 jQuery 选择器优先于其他选择器

javascript - 启用/禁用 jquery ui 组件

javascript - 在 Angular 应用程序之外使用 angular2 服务

javascript - 当我阅读react的文档时,我对以下单词感到困惑

javascript - ReactJS - 单击时容器 div 的访问键?

javascript - 修改嵌套的 redux 状态而不发生变异

javascript - ReactDOM.render 不接受 JSX