如何制作调用 setUserContext 的可重用函数? React Hooks 使用上下文
How to make a reusable function that calls setUserContext? React Hooks useContext
所以我有 4 个组件,它们都在 onClick 处理程序中做同样的事情。
我必须在其中的每一个中定义此代码。
我不知道如何使它可重用的原因是您不能在常规非反应实用程序函数内调用 setUserContext。我尝试创建一个挂钩,但您不能将挂钩用作 onClick 内的回调。
我有哪些选择?
const { userContext, setUserContext } = useContext(UserContext);
// this goes inside onClick and is defined in like 4 components (too much repetition)
const favoriteItem = (e) => {
e.stopPropagation();
e.preventDefault();
setUserContext({ ...userContext, favoriteItems: JSON.parse(localStorage.getItem("favoriteItems")) });
}
您可以创建自定义挂钩。
const useCustomHook = () => {
const { userContext, setUserContext } = useContext(UserContext);
const favoriteItem = (event, game) => {
e.stopPropagation();
e.preventDefault();
setUserContext({ ...userContext, favoriteItems: JSON.parse(localStorage.getItem("favoriteItems")) });
}
return { favoriteItem }
}
export default useCustomHook;
您的组件可以做到这一点。
...
const { favoriteItem } = useCustomHook()
return (
<Element onClick={(event) => favoriteItem(event, game)} />
)
...
所以我有 4 个组件,它们都在 onClick 处理程序中做同样的事情。
我必须在其中的每一个中定义此代码。
我不知道如何使它可重用的原因是您不能在常规非反应实用程序函数内调用 setUserContext。我尝试创建一个挂钩,但您不能将挂钩用作 onClick 内的回调。
我有哪些选择?
const { userContext, setUserContext } = useContext(UserContext);
// this goes inside onClick and is defined in like 4 components (too much repetition)
const favoriteItem = (e) => {
e.stopPropagation();
e.preventDefault();
setUserContext({ ...userContext, favoriteItems: JSON.parse(localStorage.getItem("favoriteItems")) });
}
您可以创建自定义挂钩。
const useCustomHook = () => {
const { userContext, setUserContext } = useContext(UserContext);
const favoriteItem = (event, game) => {
e.stopPropagation();
e.preventDefault();
setUserContext({ ...userContext, favoriteItems: JSON.parse(localStorage.getItem("favoriteItems")) });
}
return { favoriteItem }
}
export default useCustomHook;
您的组件可以做到这一点。
...
const { favoriteItem } = useCustomHook()
return (
<Element onClick={(event) => favoriteItem(event, game)} />
)
...