我正在学习如何正确使用 ReactHooks。我遇到了如下所述的问题:
我正在使用第三方库的 Nav 组件。我使用钩子的组件如下所示:
//using redux selector to get value from state
const { screenType } = useSelector((state: IStateStore) => ({
screenType: state.screenType
}));
// dummy use effect to see when store's screentype is being updated
React.useEffect(() => {
console.log("screentype in effect", screenType); //prints updated when store changes
}, [screenType]);
//onRender callback I pass to my third party component
const onRenderLink = (link: INavLink) => {
console.log("Screen Type inside :", screenType);//never gets executed after screentype updates
return (<>Hello</>);
};
return (
<Navigation
groups={[]}
onRenderLink={onRenderLink}
/>
</div>
);
};
我的问题是:
- 当我的组件渲染时,调用 onRenderLink,它使用来自存储的默认 screenType 值调用我的函数 onRenderLink。
- 当商店的 screenType 值更改时,我的 useEffect 钩子会打印更新的值,但此时我无法重新调用我的 onRenderLink,因为它之前已经调用过。
如何使 screenType 值更改再次调用 onRenderLink?我试着做。
<Navigation
className="sectionTabs"
groups={[]}
onRenderLink={React.useCallback(onRenderLink, [screenType])}
/>
我认为当 screenType 发生变化时,这将重新触发我的回调方法,但事实并非如此。 感谢您的帮助
尝试提供screenType
作为导航key
<Navigation
key={screenType}
groups={[]}
onRenderLink={onRenderLink}
/>
您需要使用 useMemo 钩子,因为您希望每次screenType
更改时都会调用onRenderLink()
并返回一个值。
它应该这样实现:
//using redux selector to get value from state
const { screenType } = useSelector((state: IStateStore) => state);
// dummy useEffect to see when store's screenType is being updated
useEffect(() => {
//prints updated screenType when store changes
console.log("screenType in useEffect", screenType);
}, [screenType]);
//onRenderLink gets invoked every time screenType updates and returns <>Hello</>
const onRenderLink = useMemo((link: INavLink) => {
//prints updated screenType when store changes
console.log("screenType in onRenderLink", screenType);
return (<>Hello</>);
},[screenType]) // need to pass screenType to dependency list
return (
<div>
<Navigation
groups={[]}
onRenderLink={onRenderLink}
/>
</div>
);
};
如果您需要对此:)进行任何进一步的解释,请告诉我