[英]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.