Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - what happens in React hooks when executing some function after settingSomeState() function in parents function

parent's clickHandler() function is called from its child, after executing setState() function What happens if on the next line is executed some other tasks ?

export default function App() {
  const [state, setState] = useState("initial state");

  const clickHandler = (e) => {
    console.log("onclick", state);
    setState(e.target.innerText);
    console.log("onclick", state);
  };

  return (
    <div className="App">
      <Child clickHandler={clickHandler} />
    </div>
  );
}


function Child({ clickHandler }) {
  return (
    <div className="Child">
      <button onClick={clickHandler}>Click me</button>
    </div>
  );
}

I am getting result onclick initial state two times, but I suppose to get onclick initial state first and onclick Click me second, or nothing at second time, why anyway it logs on secont time, does not setState supposed to cause rerender no matter what's next to execute in this function?

question from:https://stackoverflow.com/questions/66055148/what-happens-in-react-hooks-when-executing-some-function-after-settingsomestate

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

1 Answer

0 votes
by (71.8m points)

setState() from useState is executed asynchronously. Once the state is actually set it will trigger a re-render. Your second console.log will not reliably have the accurate state.

If you want something else to happen after state has been set you can use a useEffect like this.

useEffect(() => {
  console.log("State is:", state);
},[state]);

This will fire on load, and every time state is updated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...