javascript - 如何制作一个调用 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")) });
}
解决方案
您可以创建自定义挂钩。
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)} />
)
...
推荐阅读
- scala - 如何使用scala从json var中删除键值
- php - MYSQL多词搜索结果
- ruby-on-rails - Ruby 调用 Python 脚本会导致德语字符出现编码错误
- ruby-on-rails - 如何确定一个对象是否适合 cookie 缓存或不在 Rails 中
- python - Flask - 在 Ajax/JQuery 中更新页面内容而不进行重定向
- node.js - GraphQL 架构定义错误
- ansible - 在 Ansible Jinja2 模板中验证 yaml 路径
- php - 是否可以有 3 个 div 元素并让循环按顺序填充它们?
- c# - 将对象/动态作为 DataGridView
- python - 在带有邻近运算符的 python 的文本中找到(两个)相邻的单词。可扩展的解决方案