[英]React component's state change from constructor to componentDidMount is not effecting Render?
[英]logic at initialization of the state/constructor vs ComponentDidMount in React
我正在檢查我的代碼並意識到我有時在 ComponentDidMount 聲明 state 和其他時間時分配邏輯。
constructor(props) {
super(props);
this.state = {
api: localStorage.getItem("api") ? true : false,
};
其他時候我這樣做
constructor(props) {
super(props);
this.state = {
api: null,
};
componentDidMount() {
this.setState({api: localStorage.getItem("api") ? true : false})
}
它們的行為方式似乎相同,但我確信存在一些細微差別。 哪一個是最正確的?
作為 react 中語句的執行流程,我個人使用構造函數來存根或初始化函數/變量/參數或在執行渲染后將函數設置為就緒。 React 文檔要求您在構造函數本身中初始化 state 的原因是在其中設置預定義值,以便何時執行 componentWillMount(deprecated) 可以與道具進行比較。
在這里,您的 localstorage get item 可以工作,因為這些是 window 或瀏覽器定義的語句或 JS 函數,如果您將它們寫在 class 或 function 之外,它們仍然可以工作。 他們不依賴於 function 或 class 的行為方式。
ComponentDidMount 應該是設置值或在組件中做一些時髦的事情的模式。 由於它在渲染之后執行,因此它具有各種有用的功能,例如異步調用或 setState 或 set ref,例如:您在 didMount 中執行 setState 的方式是設置組件的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.