Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

javascript - React hooks stale state

I'm trying to call setState asynchronous in a callback, the issue is that by the time my function calls setState, the state was updated by another event that happened. Is there a way to query the current state from a nested callback?

Here's a simple demo that showcases what I'm running into:

https://stackblitz.com/edit/react-uybyyn

import React, { Component, useState } from 'react';
import { render } from 'react-dom';

function App() {
  const [state, setState] = useState({value: 0});
  const click = async () => {

    setTimeout(() => setState({value: state.value + 10}), 300);

    async function apiCall(state) {
      // fake it for now
      return new Promise((res) => {
        setTimeout(() => {
          // !!!Get the latest state here!!!
          res({value: state.value + 1});
        }, 1000)
      });
    }

    const newState = await apiCall(state);
    setState(newState);
  }
  return (
    <div>
      Value: {state.value}
      <button onClick={click}>Update</button>
    </div>
  );
}

render(<App />, document.getElementById('root'));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

useState has a function updater form. You can use that to get the latest state value before updating.

const [val ,setVal] = React.useState(initVal);

const obj = { str: 'Hello' };

// Merge state form —
seVal(obj);

// Function updater form —
seVal(prevState => {
  // Object.assign would also work
  return {...prevState, ...{ str: prevState.str + ' World' }};
});

So your example would become

setTimeout(() => setState(prevState => ({value: prevState.value + 10})), 300);

Ref to docs — hooks-reference.html#functional-updates

I have also updated your codesandbox to get it to work with comments. codesandbox


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...