gpt4 book ai didi

javascript - 使用 react.js 立即强制重新渲染(更新状态并更新 DOM)

转载 作者:可可西里 更新时间:2023-11-01 02:08:30 26 4
gpt4 key购买 nike

我意识到调用setState 不会立即更新this.state,也不会立即调用render 并刷新DOM。文档说

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

我希望能够在任何时候强制执行这样的“状态转换”。这似乎应该是一个相当自然的操作,但我在文档中找不到任何提及。有办法吗?

最佳答案

您可以为此使用forceUpdate:

If your render() method reads from something other than this.props or this.state, you'll need to tell React when it needs to re-run render() by calling forceUpdate(). You'll also need to call forceUpdate() if you mutate this.state directly.

https://facebook.github.io/react/docs/component-api.html#forceupdate

关于javascript - 使用 react.js 立即强制重新渲染(更新状态并更新 DOM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30838602/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com