首页 > 解决方案 > 如何制作一个调用 setUserContext 的可重用函数?React Hooks 使用上下文

问题描述

所以我有 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")) });
  }

标签: javascriptreactjsreact-hooksuse-context

解决方案


您可以创建自定义挂钩。

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)} /> 
) 
... 

推荐阅读