正在加载视频...

视频加载失败

"Why can't I access an updated state value in React immediately?"

142,247 次观看 • 3 年前 •via X (Twitter)

9 条评论

Alex Sidorenko 的头像
Alex Sidorenko3 年前

Because it's not how React works. Updating a state in React triggers a new render (React calls your component function again with a new state). You can access the updated state variable during this new render.

Shyam Makwana 的头像
Shyam Makwana3 年前

Other solution is to use callback function like:

Neo 🍍🍍 的头像
Neo 🍍🍍3 年前

There’s a callback on setState if you need it immediately

Bilal Tamerhoulet 🇩🇿 🇵🇸 的头像
Bilal Tamerhoulet 🇩🇿 🇵🇸3 年前

State updates are asynchronous

harpaljadeja.eth (evm/acc) 🇮🇳 的头像
harpaljadeja.eth (evm/acc) 🇮🇳3 年前

So what's the solution?

🦭x 的头像
🦭x3 年前

Closure

Eberechi 的头像
Eberechi3 年前

React batches changes and updates only after the whole function is done running. Hence a log immediately after changing set only had access to the initial state.

nadim 的头像
nadim3 年前

What are you using to create this awesome code animation?

Claudio 的头像
Claudio3 年前

Nice content mate, but it never ceases to amaze me how weirdly architected React is.

相关视频