React setTimeout and setState inside useEffect

邮差的信 提交于 2021-02-10 14:17:38

问题


I have this code and my question is why inside my answer function I get the initialState. How to set the state in a proper way to get the right one inside a callback of setTimeout function?

const App = () => {
  const [state, setState] = useState({
    name: "",
    password: "",
  });

  useEffect(() => {
    setState({ ...state, password: "hello" });
    setTimeout(answer, 1000);
  }, []);

  const answer = () => {
    console.log(state);
    // we get initial State
  };
  return <div className="App"></div>;
};

回答1:


The reason is closure.

answer function will always log that value of state which setTimeout() function closed over when it was called.

In your code, since setTimeout() function is called when state contains an object with empty values, answer function logs that value, instead of logging the updated value.

To log the latest value of state, you can use useRef() hook. This hook returns an object which contains a property named current and the value of this property is the argument passed to useRef().

function App() {
  const [state, setState] = React.useState({
    name: "",
    password: "",
  });

  const stateRef = React.useRef(state);

  React.useEffect(() => {
    stateRef.current = { ...stateRef.current, password: 'hello'};
    setState(stateRef.current);
    setTimeout(answer, 1000);
  }, []);

  const answer = () => {
    console.log(stateRef.current);
  };
  return <div></div>;
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>



回答2:


The function answer is a closure other the value of state, it captures the value of a variable inside of it's scope when it's defined. When the callback inside of useEffect is called, the answer method it's got is closed over the value of the state before your setState.

That's the function with whom you'll be calling setTimeout so even if there's a timeout, the old value of the state will be delay.



来源:https://stackoverflow.com/questions/62920594/react-settimeout-and-setstate-inside-useeffect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!