[英]Using class property to set initial state in React
我有一個React類組件,在構造函數調用中帶有一個初始狀態對象。 我最初只是將一個對象常量分配給this.state,但是我需要與該類中的其他方法共享初始狀態對象以重置組件。 將初始狀態對象移動為類屬性並在構造函數中引用它可以嗎?
class SampleComponent extends Component {
constructor() {
super();
this.state = this.initialState;
}
initialState = {
property1: "...",
property2: "..."
};
}
該代碼似乎可以正常工作,但是我不確定這是否是正確的方法。
將initialState
與類分離:
const initialState = {
property1: "...",
property2: "..."
};
// As Class
class SampleComponent extends Component {
state = initialState;
...
}
// Hooks
function SampleComponent(props) {
const [myState, setMyState] = useState(initialState);
...
}
這樣,您可以避免以后有關this.initialState
錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.