Strange behavior of React hooks: delayed data update

前端 未结 3 647
走了就别回头了
走了就别回头了 2020-12-10 18:42

Strange behavior: I expect that the first and the second console.log display a different result, but they display the same result and the value is changed only on the next c

3条回答
  •  离开以前
    2020-12-10 19:15

    State updates are asynchronous. The setCount function you get from useState can't magically reach out and change the value of your count constant. For one thing, it's a constant. For another, setCount doesn't have access to it. Instead, when you call setCount, your component function will get called again, and useState will return the updated count.

    Live Example:

    const {useState} = React;
    
    function Example() {
      const [count, setCount] = useState(false);
      const test = () =>{
        setCount(!count); // Schedules asynchronous call to Example, re-rendering the component
      };
      return (
        

    Hello CodeSandbox

    Count: {String(count)}
    ); } ReactDOM.render(, document.getElementById("root"));

    If you need to perform some side-effect when count changes, use useEffect:

    useEffect(() => {
      console.log(`count changed to ${count}`);
    }, [count]);
    

    Notice that we tell useEffect to only call our callback when count changes, so that if we have other state, our callback doesn't run unnecessarily.

    Live Example:

    const {useState, useEffect} = React;
    
    function Example() {
      const [count, setCount] = useState(false);
      const test = () =>{
        setCount(!count); // Schedules asynchronous call to Example, re-rendering the component
      };
      useEffect(() => {
        console.log(`count changed to ${count}`);
      }, [count]);
      return (
        

    Hello CodeSandbox

    Count: {String(count)}
    ); } ReactDOM.render(, document.getElementById("root"));

提交回复
热议问题