简体   繁体   中英

I can't understand how this code(for React/Redux) works

I have a question for React/Redux .

I am making a web application. And it works perfectly in the way I want it to work without any problems. Even though I don't understand it. The part I don't understand is this part.

This is my code.

const myApps = () => {
  let myInfo = {};
  const form = [];
  form.push(<div>what</div>);
  myInfo = form.reduce((prev, element, index) => {
    prev[index] = {isTrue : false};
    return prev;
  }, {});
}

useEffect(() => {
    uploadToRedux(myInfo); // this is redux dispatch. I upload to redux "only" here.
}, []);

myInfo[0].isTrue = true;

if (myInfo[0].isTrue) console.log('Correct!');
else console.log('Incorrect!');

I'm sending myInfo to Redux only if it's componentDidMount by using useEffect . By the way, When I switch myInfo[0].isTrue = true , the state in the redux changes simultaneously. Even though I didn't send a dispatch!

Of course, this is what I want, but is there any change in the state in redux even if I didn't send the dispatch? How could this be?

As I know, you need to dispatch yourself when you request a server (API) to return data to you. So it needs to be async .but when it's not async you just pass the data to store and it will dispatch itself.

So whenever your data comes back after a delay it's an async request and you need dispatch data when you received data. (if you don't you may get an error because redux dispatch an undefined data)

I hope it be helpful to you.

Notice that you are passing a function to useEffect() as callback.

() => {
  uploadToRedux(myInfo); // this is redux dispatch. I upload to redux "only" here.
}

useEffect() will execute immediately but the anonymous function (callback) will be scheduled to be executed by JS runtime (ie ready to be executed but in fact not executed yet).

By the time the callback is about to execute and update values in redux, JS runtime will already have executed the lines after useEffect() ie the following lines of code will be executed before redux update:

myInfo[0].isTrue = true;

if (myInfo[0].isTrue) console.log('Correct!');
else console.log('Incorrect!');

So when JS runtime will execute following line:

uploadToRedux(myInfo);

Value of myInfo[0].isTrue will already be updated and same will go to redux.

The phenomena is called Callback Hell. To know more about it, read this: http://callbackhell.com/

To be sure, log the value of myInfo[0].isTrue before redux update

useEffect(() => {
  console.log("myInfo[0].isTrue", myInfo[0].isTrue);
  uploadToRedux(myInfo); // this is redux dispatch. I upload to redux "only" here.
}, []);

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