简体   繁体   English

使用类属性在React中设置初始状态

[英]Using class property to set initial state in React

I have a React class component that with an initial state object in the constructor call. 我有一个React类组件,在构造函数调用中带有一个初始状态对象。 I originally just had an object literal assigned to this.state, but I need to share the initial state object with other methods in the class to reset the component. 我最初只是将一个对象常量分配给this.state,但是我需要与该类中的其他方法共享初始状态对象以重置组件。 Is it ok/correct to move the initial state object to be a class property and reference that in the constructor? 将初始状态对象移动为类属性并在构造函数中引用它可以吗?

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

    this.state = this.initialState;
  }

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

The code seems to work, but I'm not sure if this is the right way to go about this. 该代码似乎可以正常工作,但是我不确定这是否是正确的方法。

Decouple the initialState from the class: initialState与类分离:

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

// As Class
class SampleComponent extends Component {
  state = initialState;
  ...
}

// Hooks
function SampleComponent(props) {
  const [myState, setMyState] = useState(initialState);
  ...
}

In this way, you avoid future bugs regarding this.initialState . 这样,您可以避免以后有关this.initialState错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用对象引用在React中设置初始状态 - Using an object reference to set initial state in react 如何在反应 class 组件中设置另一个 state 以将数据从初始 state 传递到 - How can I set another state to pass data to from the initial state in a react class component 如何使用react和typescript根据formfield的值将react state设置为一些初始state? - How to set react state to some initial state based on the value of formfield using react and typescript? 使用异步/等待变量反应设置初始 state - react set initial state with async/await variable 如何在React上使用undo操作设置初始状态? - How to set initial state with undo action on React? 从 React 组件中的 props 设置初始状态 - Set initial state from props in React componenet react native state 已更新,但功能仍使用安装时设置的初始 state - react native state is updated but functions still using the initial state set at the time of mounting 设置类使用状态,如果其他,则带有react获取未定义错误的状态 - set class using state if else with react gets state of undefined error 如何使用 react-navigation v5 设置初始状态以将屏幕包含为历史记录? - How can I set the initial state using react-navigation v5 to include screens as history? 在React中填充初始状态 - Populating Initial State in React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM