React 組件中的state和setState()你知道多少
state的基本使用
狀態(tài)(state)即數(shù)據(jù),是組件內(nèi)部的私有數(shù)據(jù),只能在組件內(nèi)部使用
state的值是對象,可以通過this.state來獲取狀態(tài)。
setState()修改狀態(tài)
狀態(tài)是可變的,可以通過this.setState({要修改的數(shù)據(jù)})來改變狀態(tài)
注意:跟vue語法不同,不要直接修改state中的值,這時錯誤的!
//正確
this.setState({
count:this.state.count+1
})
//錯誤
this.state.count+=1最后結(jié)合以上內(nèi)容,寫了一個簡單的累加器,但是在此之前,我們需要解決this在自定義的方法中的指向問題,否則this指向會為undefined,我們一般希望this指向組件實例。
解決方法:
1.箭頭函數(shù)
利用箭頭函數(shù)自身不綁定this的特點
class App extends React.Component{
state={
count:0,
}
render(){
// 箭頭函數(shù)中的this指向外部韓靜,此處指向render()方法
return (
<div>
<span>總數(shù):{this.state.count}</span>
<button onClick={()=>{
this.setState({
count:this.state.count+1
})
}}>點擊+1</button>
</div>
)
}
}
ReactDOM.render(<App/>,document.getElementById('root'));但是這種方法會導(dǎo)致JSX語法中代碼過于繁雜,不利于表明項目結(jié)構(gòu),一般不推薦使用。
2.Function.prototype.bind()
利用ES5中的bind方法,將事件處理程序中的this與組件示例綁定到一起
class App extends React.Component{
constructor(){
super()//super()必須寫,這時ES6語法中class的一個要求
//此時可將state放到constructor()中
this.state={
count:0,
}
this.add=this.add.bind(this)//將this指向綁定到實例
}
//事件處理程序
add(){
this.setState({
count:this.state.count+1
})
}
render(){
// 箭頭函數(shù)中的this指向外部韓靜,此處指向render()方法
return (
<div>
<span>總數(shù):{this.state.count}</span>
<button onClick={this.add}>點擊+1</button>
</div>
)
}
}
ReactDOM.render(<App/>,document.getElementById('root'));3.class的示例方法
利用箭頭函數(shù)形式的class實例方法,此方法比較簡潔,強烈推薦
注意:該語法是實驗性語法,但是由于腳手架中babel的存在,可以直接使用
class App extends React.Component{
state={
count:0,
}
add=()=>{
this.setState({
count:this.state.count+1
})
}
render(){
// 箭頭函數(shù)中的this指向外部韓靜,此處指向render()方法
return (
<div>
<span>總數(shù):{this.state.count}</span>
<button onClick={this.add}>點擊+1</button>
</div>
)
}
}
ReactDOM.render(<App/>,document.getElementById('root'));總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
React之如何在Suspense中優(yōu)雅地請求數(shù)據(jù)
Suspense 是 React 中的一個組件,直譯過來有懸掛的意思,能夠?qū)⑵浒漠惒浇M件掛起,直到組件加載完成后再渲染,本文詳細介紹了如何在Suspense中請求數(shù)據(jù),感興趣的小伙伴可以參考閱讀本文2023-04-04
React配置Redux并結(jié)合本地存儲設(shè)置token方式
這篇文章主要介紹了React配置Redux并結(jié)合本地存儲設(shè)置token方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
React+Redux實現(xiàn)簡單的待辦事項列表ToDoList
這篇文章主要為大家詳細介紹了React+Redux實現(xiàn)簡單的待辦事項列表ToDoList,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-09-09

