現在來寫寫有關setState的用法,代碼如下:
// Testsetstate.js 文件
import React, {Component} from 'react'
class testSetState extends Component {
constructor(props){
super(props)
this.state = {
count: 0
}
}
increment(){
this.setState(
{
count: this.state.count + 1
},
() => {
console.log("After", this.state.count)
}
)
}
render() {
return (
<div>
Count - {this.state.count}
<button onClick={() => this.increment()}>
Increment
</button>
</div>
)
}
}
export default testSetState;
在App.js文件中,
// App.js 文件
import React from 'react';
import './App.css';
import Testsetstate from './Testsetstate'
function App() {
return (
<div className="App">
<Testsetstate/>
</div>
);
}
export default App;
結果如下:
當點擊Increment按鈕時,就會實現增加效果:
在console 裏就會出現這個結果:
如果爲了實現一次性增加5呢,有兩種做法:
第一種: 改變 ”count: this.state.count + 1“ 成爲 ” count: this.state.count + 5“
第二種:這種辦法看起來比較差,但是是爲了說明如何在react中函數去調用其他函數
// Testsetstate.js 文件
import React, {Component} from 'react'
class testSetState extends Component {
constructor(props){
super(props)
this.state = {
count: 0
}
}
increment(){
this.setState(prevState => ({
count: prevState.count + 1
}))
console.log(this.state.count)
}
incrementFive() {
// 調用increment() 函數五次
this.increment();
this.increment();
this.increment();
this.increment();
this.increment();
}
render() {
return (
<div>
Count - {this.state.count}
<button onClick={() => this.incrementFive()}>
Increment
</button>
</div>
)
}
}
export default testSetState;
App.js 文件不用修改。
結果如下:
當點擊Increment按鈕時,會出現這個結果:
現在總結setState一下:
- Always make use of setState and never modify the state directly
- Code has to be executed after the state has been updated? Place that code in the call back function which is the second argument to the setState method.
- When you have to update state based on the previous state value, pass in a function as an argument instead of the regular object.
如果覺得寫的很好,就給個贊來代替五星好評哦!