[英]How to access state/redux store in the useEffect's cleanup function?
[英]Return undefined Redux store state in useEffect() function
我的 Redux 商店 state 在useEffect
掛鈎中返回未定義。 如果我刪除 useEffect 中的空數組[]
,我的useEffect
存儲返回true
值,但非常多,有時會在無限循環中執行!
useEffect(() => {
store.subscribe(() => {
setNodeProperties({
positionX: store.getState().schemaViewer.positionX,
positionY: store.getState().schemaViewer.positionY,
});
console.log(nodeProperties);
});
}, []);
問題是setNodeProperties
會將nodeProperties
的更改排隊,並且不會立即發生,因為它是異步的。 因此,一旦nodeProperties
發生變化,我會嘗試產生副作用。 您的組件中可以有多個useEffect
掛鈎。
嘗試如下:
useEffect(() => {
console.log(nodeProperties);
}, [nodeProperties]);
通過這種方式,您將捕獲nodeProperties
的更改並僅在那時運行日志記錄步驟。 建議閱讀使用效果掛鈎。
我希望這有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.