setState
1. 在 React 的事件中,表现为异步
changeCount = () => {
this.setState({
count: this.state.count + 1
})
console.log(this.state.count)
}
<button onClick={this.changeCount}>add</button>
2. 在原生事件中,表现为同步
componentDidMount() {
this.btn.current.addEventListener('click', ()=>{
this.setState({
count: this.state.count + 1
})
console.log('原生', this.state.count)
}, false);
}
<button ref={this.btn}>原生add</button>
如何在React的事件中表现同步呢? 可以给setState 添加回调函数:
this.setState({
count: 100
}, ()=>{
console.log('回调', this.state.count)
})
在React中,setState 有两种写法: 1. 用对象的方式
this.setState({
count: 100
})
2. 用函数的方式
this.setState((state, props) => {
return {
count: 100
}
}
完整代码
import React, { Component } from 'react';
class SetStateDemo extends Component {
constructor() {
super();
this.state = {
count: 1
}
this.btn = React.createRef();
}
changeCount = () => {
this.setState({
count: this.state.count + 1
})
console.log(this.state.count)
}
changeCount_call = () => {
this.setState({
count: this.state.count + 1
}, ()=>{
console.log('回调', this.state.count)
})
}
changeCount_fn = () => {
this.setState((state, props) => {
return {
count: state.count + 1
}
}, ()=>{
console.log('fn 回调', this.state.count)
})
console.log('fn', this.state.count)
}
componentDidMount() {
this.btn.current.addEventListener('click', ()=>{
this.setState({
count: this.state.count + 1
})
console.log('原生', this.state.count)
}, false);
}
render() {
return (
<div>
<div>{this.state.count}</div>
<button onClick={this.changeCount}>add</button>
<button onClick={this.changeCount_call}>回调add</button>
<button onClick={this.changeCount_fn}>fn add</button>
<button ref={this.btn}>原生add</button>
</div>
);
}
}
export default SetStateDemo;
|