1. 不要直接修改State
2. state的更新可能是异步的
3. state的更新会合并
正确使⽤setState
setState(partialState, callback)
- partialState : object|function
⽤于产⽣与当前state合并的⼦集。 - callback : function
state更新之后被调⽤。
不要直接修改 State
// 错误示范
this.state.comment = 'Hello';
// 正确使⽤
this.setState({comment: 'Hello'});
State 的更新可能是异步的
import React, { Component } from "react";
export default class SetStatePage extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
}
changeValue = v => {
this.setState({
counter: this.state.counter + v
});
console.log("counter", this.state.counter);
};
setCounter = () => {
this.changeValue(1);
};
render() {
const { counter } = this.state;
return (
<div>
<h3>SetStatePage</h3>
<button onClick={this.setCounter}>{counter}</button>
</div>
);
}
console.log("counter", this.state.counter); 每次打印的结果都是上一次的,而不是最新的
解决办法
1.在回调中获取状态值
changeValue = v => {
this.setState(
{
counter: this.state.counter + v
},
() => {
console.log("counter", this.state.counter);
}
);
};
- 使⽤定时器:
setTimeout(() => {
this.setCounter();
}, 0);
- 原⽣事件中修改状态
componentDidMount(){
document.body.addEventListener('click', this.changeValue, false) }
推荐第一种,第二种可能会多一次dom渲染
State 的更新会被合并
changeValue = v => {
this.setState({
counter: this.state.counter + v
});
};
setCounter = () => {
this.changeValue(1);
this.changeValue(2);
};
this.changeValue(2); 会覆盖this.changeValue(1); 最终结果是counter + 2 而不是 + 3
解决办法
changeValue = v => {
this.setState(state => ({ counter: state.counter + v }));
};
setCounter = () => {
this.changeValue(1);
this.changeValue(2);
};
setState第一个参数传一个函数,return { state的属性名: 属性值 }
网友评论