【问题标题】:How can I initialize Redux state for React component on its creation?如何在创建 React 组件时为其初始化 Redux 状态?
【发布时间】:2020-02-18 15:03:09
【问题描述】:

我有一个带有渲染组件的路由(使用 React-Router)。每次打开此路由并创建其组件时,我都需要重置该组件中使用的 Redux 状态的某些部分(实际上是一个 reducer 的状态)。这个 reducer 在应用程序的其他一些部分共享,所以我使用 Redux 状态而不是本地组件的状态。那么如何在每次创建组件时重置减速器的状态呢?我想知道执行此操作的最佳做​​法。

  • 我想如果我在 componentDidMount 方法中调度动作,之前的状态会闪烁几秒钟。

  • 我可以在组件的构造函数中调度操作来重置一些减速器的状态吗?

  • 有没有更好的方法?我可以以某种方式在 connect() 函数中设置初始状态,因此每次创建组件时都会重置状态?我检查了文档,但找不到相关的论据。

【问题讨论】:

    标签: javascript reactjs react-redux react-router


    【解决方案1】:

    是的,您可以在构造函数中调度操作以更改减速器状态

    constructor(prop){
        super(prop);
        prop.dispatch(action);
    }
    

    您可以尝试的另一种方法是设置默认道具,这样您就不需要调用 reducer(dispatch action)

    ButtonComponent.defaultProps = {
      message: defaultValue,
    };
    

    【讨论】:

      【解决方案2】:

      我能想到的一种可能的解决方案...

      如果您可以使用第一种方法,您可以尝试在使用重置状态重新渲染组件时停止显示先前的状态。

      您会看到 prevState 的唯一阶段是在初始渲染期间。一个实例变量来跟踪渲染计数怎么样。

      草稿。

      import React from "react";
      import { connect } from "react-redux";
      import { add, reset } from "./actions";
      class Topics extends React.Component {
      
        renderCount = 0;
      
        componentDidMount() {
          // Dispatch actions to reset the redux state
          // When the connected props change, component should re-render
          this.props.reset();
        }
      
        render() {
          this.renderCount++;
          if (this.renderCount > 1) {
            return (
              <div>
                {this.props.topics.map(topic => (
                  <h3 id={topic}>{topic}</h3>
                ))}
              </div>
            );
          } else {
            return "Initializing"; // You can return even null
          }
        }
      }
      
      const mapStateToProps = state => ({ topics: state });
      const mapDispatchToProps = (dispatch) => {
        return {
      
          add(value){
            dispatch(add(value));
          },
          reset(){
            dispatch(reset());
          }
        }
      }
      
      export default connect(mapStateToProps, mapDispatchToProps)(Topics);
      

      这里renderCount 是一个类变量,它在组件render 上不断增加。在第一次渲染时显示后备 UI 以避免显示之前的状态,在第二次渲染时(由于 redux 存储更新),您可以显示存储数据。

      下面添加了一个工作示例。我还添加了一种避免回退 UI 的方法。看看有没有帮助。

      https://stackblitz.com/edit/react-router-starter-fwxgnl?file=components%2FTopics.js

      【讨论】:

        猜你喜欢
        • 2016-03-09
        • 1970-01-01
        • 2018-07-23
        • 2021-09-11
        • 2023-03-08
        • 1970-01-01
        • 2016-09-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多