简体   繁体   中英

Using React states with delay

I am using a library called react-easy-state for my state management but I believe this questions is not directly related to this library rather a general question.

Having a code like this in my App.js:

function App() {
  const [isChanged, setIsChanged] = React.useState(false);
  console.log(store.counter);
  React.useEffect(() => {
    setTimeout(() => {
      setIsChanged(true);
    }, store.counter);
  }, []);

  return (
    <div className="App">
      {isChanged && <h1>Hello CodeSandbox</h1>}
      <Change />
    </div>
  );
} 

Which has a child <Changed /> that looks like this:

export default function Change() {
  React.useEffect(() => {
    store.rndNum = ~~(Math.random() * 6) + 11;
  }, []);

  store.counter = ~~Math.pow(1.555, store.rndNum) * 20;

The child is supposed to generate a random number and then modify the random number and store it in another variable in my store. The modified value is supposed to slow down the appearance of an HTML element which toggled and triggered by setTimeout . However my console shows that number that is being generated is not matching with my code and as it generates 20 for some reason and then proceeds to generate the correct number. In the mean time I would like to wait until the value in my store in updated and then run setTimeout . Whereas currently setTimeout takes either 0 or 20 as the timer and executes the code without any delay.

code to reproduce: https://codesandbox.io/s/hopeful-cdn-vg7kh

You are getting 20 first because of this operation.

store.counter = ~~Math.pow(1.555, store.rndNum) * 20;

Why? Because store.rndNum at that time is still "" (declared on store as "") and this part

~~Math.pow(1.555, store.rndNum)

will always be 1.

Hooks are asynchronous, so useEffect will not change the rndNum value first.

Edit for my comment:

 React.useEffect(() => {
    if (!isNaN(store.rndNum)) {
      store.counter = ~~Math.pow(1.555, store.rndNum) * 20;
    }
  }, [store.rndNum]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM