【问题标题】:Using class property to set initial state in React在 React 中使用类属性设置初始状态
【发布时间】:2019-06-02 18:02:08
【问题描述】:

我有一个 React 类组件,它在构造函数调用中有一个初始状态对象。我最初只是为 this.state 分配了一个对象字面量,但我需要与类中的其他方法共享初始状态对象来重置组件。将初始状态对象移动为类属性并在构造函数中引用它是否可以/正确?

class SampleComponent extends Component {
  constructor() {
    super();

    this.state = this.initialState;
  }

  initialState = {
    property1: "...",
    property2: "..."
  };
}

代码似乎可以工作,但我不确定这是否是正确的方法。

【问题讨论】:

    标签: javascript reactjs class state


    【解决方案1】:

    initialState 与类解耦:

    const initialState = {
        property1: "...",
        property2: "..."
    };
    
    // As Class
    class SampleComponent extends Component {
      state = initialState;
      ...
    }
    
    // Hooks
    function SampleComponent(props) {
      const [myState, setMyState] = useState(initialState);
      ...
    }
    

    通过这种方式,您可以避免将来出现关于 this.initialState 的错误。

    【讨论】:

    • 感谢您的回复。将那个对象移到类之外是完全有意义的。 ?
    猜你喜欢
    • 2018-03-24
    • 2020-11-02
    • 2018-12-20
    • 2019-09-02
    • 1970-01-01
    • 2018-06-10
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多