简体   繁体   English

在反应中访问组件 state

[英]Accessing component state in react

I am interested in understanding why setting a components state (setState()) is slow to update ie I may read an old value after the fact that I called setState().我有兴趣了解为什么设置组件 state (setState())更新缓慢,即我可能会在调用 setState() 之后读取旧值。 Additionally i am interested in knowing if reading the component state also incurs a penalty to know if I should minimize the number of reads/writes to component state. I tried looking for the documentation at the react website but no dice.此外,我有兴趣知道读取组件 state 是否也会受到惩罚,以了解我是否应该尽量减少对组件 state 的读/写次数。我尝试在 React 网站上查找文档,但没有骰子。 Thanks谢谢

setState() is asynchronous, so you won't get the new value in the same function where you update it setState()是异步的,因此您不会在更新它的同一个 function 中获得新值

React batch multiple setState() calls into a single update for performance.将多个 setState() 调用批处理为单个更新以提高性能。 Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state. https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous因为 this.props 和 this.state 可能会异步更新,所以你不应该依赖它们的值来计算下一个state。https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-是异步的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM