现在来写写有关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.
如果觉得写的很好,就给个赞来代替五星好评哦!