import React from "react";
class Counter extends React.Component {
state = {
count: 0,
};
handleAdd = () => {
const { count } = this.state;
this.setState({
count: count + 1,
});
console.log(count); // 由于是异步的,这里输出0
};
render() {
const { count } = this.state;
return <button onClick={this.handleAdd}>{count}</button>;
}
}
如何获取改变后的值
- 方法一,通过setState的回调函数
handleAdd = () => {
// 方法一
this.setState(
{
count: count + 1,
},
() => {
console.log(count);// 1
},
);
}
- 方法二,通过setTimeout
handleAdd = () => {
// 方法二
setTimeout(() => {
this.setState({
count: count + 1,
});
console.log(count);// 1
}, 0);
}
网友评论