简体   繁体   中英

Return undefined Redux store state in useEffect() function

My Redux store state return undefined in useEffect hook. If I remove empty array [] in useEffect , my Redux store return true value but very much and sometimes executed in an endless loop!

 useEffect(() => {
    store.subscribe(() => {
      setNodeProperties({
        positionX: store.getState().schemaViewer.positionX,
        positionY: store.getState().schemaViewer.positionY,
      });
        console.log(nodeProperties);
    });
  }, []);

The problem is setNodeProperties will queue up the change for nodeProperties and it won't happen right away because it is asynchronous. So I would try to run a side effect once nodeProperties is changing. You can have multiple useEffect hooks in your component.

Try as the following:

useEffect(() => {
   console.log(nodeProperties);
}, [nodeProperties]);

In this way you are capturing changes for nodeProperties and run the logging step only then. Suggested read is Using the Effect Hook .

I hope this helps!

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