我有一个 React 类组件,它在构造函数调用中有一个初始状态对象。我最初只是将一个对象文字分配给 this.state,但我需要与类中的其他方法共享初始状态对象以重置组件。将初始状态对象移动为类属性并在构造函数中引用它是否可以/正确?class SampleComponent extends Component { constructor() { super(); this.state = this.initialState; } initialState = { property1: "...", property2: "..." };}该代码似乎有效,但我不确定这是否是解决此问题的正确方法。
1 回答

慕桂英3389331
TA贡献2036条经验 获得超8个赞
initialState从类中解耦:
const initialState = {
property1: "...",
property2: "..."
};
// As Class
class SampleComponent extends Component {
state = initialState;
...
}
// Hooks
function SampleComponent(props) {
const [myState, setMyState] = useState(initialState);
...
}
通过这种方式,您可以避免将来出现关于this.initialState.
添加回答
举报
0/150
提交
取消