react的this.setState詳細介紹


this.setState是react類組件中最常用的一個react API,使用它可以改變state從而改變頁面。今天我們就來詳細的學習一下這個東西。
比如:

import React, { Component } from react;

export default class Test extends Component {
constructor() {
super()
this.state = { 
count: 0,
}
}
render() {
return (
<div>
您的點擊數:{this.state.count}
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
點擊數+1
</button>
</div>

 


這樣當你每點擊button按鈕一次,上面的點擊數就會+1
但是this.setState還有很多的知識點你沒有了解,真正項目當中可能會出現很多你不理解的bug。
比如說:

this.setState是異步的
在你調用了this.setState后在他的下面輸出他的結果還是沒變的狀態

this.setState({ count: this.state.count + 1 })
console.log(this.state.count)    //結果還是之前的,而不是+1之后的

 


this.setState的第一個參數可以是一個對象,也可以是一個函數返回一個對象,函數的參數是上一次的state
示例:

this.setState((prevState) => ({ prevState.count + 1 }));

 



this.setState的第二個參數是它的回調函數,在前面重新給state賦值后執行
示例:

this.setState({
count: this.state.count + 1,
}, () => console.log(this.state.count)) //結果是+1之后的count

 



連續調用this.setState的結果
示例:

this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 1 })

 



雖然調用了三次 setState ,但是 count 的值還是為 1。因為多次調用會合並為一次,只有當更新結束后 state 才會改變,三次調用等同於如下代碼

Object.assign( 
{},
{ count: this.state.count + 1 },
{ count: this.state.count + 1 },
{ count: this.state.count + 1 },
)

 



如果想讓最后的結果等於3請用上面介紹的this.setState()的參數為函數返回對象的形式。
或者像下面這樣:

額外注意點

但是如果把上面的代碼改裝一下效果就不一樣了

setTimeout(() => {
this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 1 })
}, 100)



這時候這三次都會被執行到。

原因是因為React的更新策略沒有被觸發到。

原文鏈接:https://blog.csdn.net/weixin_43606158/article/details/94356884


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM