老师怎么实现setState 的同步?
除了老师讲的,setState第二个参数用回调函数;
网上有人提在异步逻辑比如setTimerout里面使用setState、或者在原生dom事件上使用setState,这两种情况下是同步的;
但是setTimerout这种情况我试了一下根本不行,为什么这么多人说这样可行呢?
https://www.jb51.net/article/229017.htm#_label3
class Ee extends React.Component{
constructor(props) {
super(props);
this.state = {count:0};
}
componentDidMount() {
setTimeout(() => {
this.setState({ count: this.state.count + 1 });
console.log(this.state.count); // 老师这里还是输出的是0
}, 0);
}
render() {
return (
<>
<div>当前计数:{this.state.count}</div>
<button>add</button>
</>
);
}
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Ee/>);14
收起
正在回答 回答被采纳积分+1
1回答

恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星