- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想知道操作和公开新的 React Context 的推荐最佳实践是什么。
操纵上下文状态的最简单方法似乎是将一个函数附加到上下文,该函数可以调度 (usereducer
) 或 setstate (useState
) 来更改其内部调用一次的值。
export const TodosProvider: React.FC<any> = ({ children }) => {
const [state, dispatch] = useReducer(reducer, null, init);
return (
<Context.Provider
value={{
todos: state.todos,
fetchTodos: async id => {
const todos = await getTodos(id);
console.log(id);
dispatch({ type: "SET_TODOS", payload: todos });
}
}}
>
{children}
</Context.Provider>
);
};
export const Todos = id => {
const { todos, fetchTodos } = useContext(Context);
useEffect(() => {
if (fetchTodos) fetchTodos(id);
}, [fetchTodos]);
return (
<div>
<pre>{JSON.stringify(todos)}</pre>
</div>
);
};
然而,我被告知直接公开和使用 react 上下文对象可能不是一个好主意,并被告知将其包装在一个钩子(Hook)中。
export const TodosProvider: React.FC<any> = ({ children }) => {
const [state, dispatch] = useReducer(reducer, null, init);
return (
<Context.Provider
value={{
dispatch,
state
}}
>
{children}
</Context.Provider>
);
};
const useTodos = () => {
const { state, dispatch } = useContext(Context);
const [actionCreators, setActionCreators] = useState(null);
useEffect(() => {
setActionCreators({
fetchTodos: async id => {
const todos = await getTodos(id);
console.log(id);
dispatch({ type: "SET_TODOS", payload: todos });
}
});
}, []);
return {
...state,
...actionCreators
};
};
export const Todos = ({ id }) => {
const { todos, fetchTodos } = useTodos();
useEffect(() => {
if (fetchTodos && id) fetchTodos(id);
}, [fetchTodos]);
return (
<div>
<pre>{JSON.stringify(todos)}</pre>
</div>
);
};
我在这里为这两个变体制作了运行代码示例:https://codesandbox.io/s/mzxrjz0v78?fontsize=14
所以现在我有点困惑这两种方法中哪一种是正确的方法?
最佳答案
直接在组件中使用useContext
绝对没有问题。然而,它强制必须使用上下文值的组件知道要使用什么上下文。
如果您希望在应用程序中有多个组件使用 TodoProvider 上下文,或者您的应用程序中有多个上下文,则可以使用自定义 Hook 来简化它
使用上下文时还必须考虑的另一件事是,您不应该在每次渲染时创建新对象,否则所有使用 context
的组件都将重新渲染,即使没有任何内容已改变。为此,您可以使用 useMemo
钩子(Hook)
const Context = React.createContext<{ todos: any; fetchTodos: any }>(undefined);
export const TodosProvider: React.FC<any> = ({ children }) => {
const [state, dispatch] = useReducer(reducer, null, init);
const context = useMemo(() => {
return {
todos: state.todos,
fetchTodos: async id => {
const todos = await getTodos(id);
console.log(id);
dispatch({ type: "SET_TODOS", payload: todos });
}
};
}, [state.todos, getTodos]);
return <Context.Provider value={context}>{children}</Context.Provider>;
};
const getTodos = async id => {
console.log(id);
const response = await fetch(
"https://jsonplaceholder.typicode.com/todos/" + id
);
return await response.json();
};
export const useTodos = () => {
const todoContext = useContext(Context);
return todoContext;
};
export const Todos = ({ id }) => {
const { todos, fetchTodos } = useTodos();
useEffect(() => {
if (fetchTodos) fetchTodos(id);
}, [id]);
return (
<div>
<pre>{JSON.stringify(todos)}</pre>
</div>
);
};
<强> Working demo
编辑:
Since
getTodos
is just a function that cannot change, does it make sense to use that as update argument inuseMemo
?
如果 getTodos 方法正在更改并在功能组件内调用,则将 getTodos
传递到 useMemo 中的依赖项数组是有意义的。通常,您会使用 useCallback 来内存该方法,以便它不会在每次渲染时创建,但仅当其封闭范围的任何依赖项发生更改以更新其词法范围内的依赖项时才创建。现在,在这种情况下,您需要将其作为参数传递给依赖项数组。
但是,就您的情况而言,您可以省略它。
Also how would you handle an initial effect. Say if you were to call `getTodos´ in useEffect hook when provider mounts? Could you memorize that call as well?
您只需在初始安装时调用的 Provider 中产生一个效果
export const TodosProvider: React.FC<any> = ({ children }) => {
const [state, dispatch] = useReducer(reducer, null, init);
const context = useMemo(() => {
return {
todos: state.todos,
fetchTodos: async id => {
const todos = await getTodos(id);
console.log(id);
dispatch({ type: "SET_TODOS", payload: todos });
}
};
}, [state.todos]);
useEffect(() => {
getTodos();
}, [])
return <Context.Provider value={context}>{children}</Context.Provider>;
};
关于reactjs - 如何操作上下文 - 将函数附加到上下文或将调度包装在钩子(Hook)中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55786752/
问题 我想在可由用户添加的表单中实现输入字段的键/值对。 参见 animated gif on dynamic fields . 此外,我想在用户提交表单并再次显示页面时显示保存的数据。 参见 ani
这个问题已经有答案了: The useState set method is not reflecting a change immediately (19 个回答) 已关闭去年。 问题是,在网页中该
这个问题已经有答案了: The useState set method is not reflecting a change immediately (19 个回答) 已关闭去年。 问题是,在网页中该
我对钩子(Hook)相当陌生,我正在尝试实现一个拖放容器组件,该组件在整个鼠标移动过程中处理 onDragStart、onDrag 和 onDragEnd 函数。我一直在尝试使用钩子(Hook)复制此
有人向我介绍了 CSS 钩子(Hook)这个术语,但我对此不是很清楚。你能给我一些想法吗? 什么是 CSS 钩子(Hook)? 最常见的钩子(Hook)是什么? 使用 CSS 钩子(Hook)的最佳做
文档 ( https://devexpress.github.io/testcafe/documentation/test-api/test-code-structure.html#test-hook
问题是包含 PR_Write() 的 DLL 调用的不是 npsr4.dll,而是 nss3.dll 和 Hook 无法从不存在的库中找到 GetProcAddress()。 我正在尝试创建 Fire
我的 git hook 似乎没有工作。即commit-msg来自 gerrit 的钩子(Hook)。 commit-msg Hook 存在于 /.git/hooks/并具有正确的语法。 最佳答案 确保
用gdb调试不熟悉的程序时,程序执行后经常会意外退出next .发生这种情况时,我通常会设置一个断点,重新运行程序并执行 step而不是 next追踪正在发生的事情。但是,有时很难知道在哪里设置断点。
当我创建一个节点时,我希望它以编程方式创建一些引用刚刚创建的节点的节点。 虽然我只需要更改表单的 form_alter 提交函数来调用自定义函数来创建节点。 检查输出 $form_state 我可以看
我是钩子(Hook)的新手,在学习了对类的 react 之后才来,所以有点迷茫。在下面的代码中,我将 setDog 更改为 Husky,然后它应该告诉 API 调用搜索并获取我的哈士奇图片。但是,尽管
我编写(进程中)钩子(Hook)以防止在本地添加 BAD 标记名称: .hg/hgrc : pretag.badtagname = python:.hg/hgcheck.py:localbadtag
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 想改进这个问题?将问题更新为 on-topic对于堆栈溢出。 7年前关闭。 Improve this qu
如果这个问题之前已经得到解答,我提前表示歉意(对于这篇长文,但我已尽力做到具体)。但是,我找到的答案并不完全令我满意。 我想在我的项目中使用新的令人惊叹的 React Hooks。到目前为止我所做的一
通过阅读一些文字,尤其是关于委托(delegate)的iOS文档,所有协议(protocol)方法都被称为 Hook 自定义委托(delegate)对象需要实现。但是其他一些书,命名为 Hook 作为
我的所有依赖项都位于受密码保护的存储库中。 我有一个要求输入用户名和密码的功能,但它经常困扰我。 有没有办法在依赖检索之前执行它? 在大多数情况下,我在本地 maven/gradle 缓存中拥有所有依
当我尝试运行 git commit -m 'message here' 时出现以下错误。 致命:无法执行 '.git/hooks/prepare-commit-msg':权限被拒绝 当我在我的 ubu
当我尝试运行 git commit -m 'message here' 时出现以下错误。 致命:无法执行 '.git/hooks/prepare-commit-msg':权限被拒绝 当我在我的 ubu
我有一个分支和主干的服务器存储库。分支是所有团队成员的存储库。我正在尝试使用 svn hooks仅在我的分支下的 repo 中,但它似乎无法正常工作。以下是我尝试采取的步骤: checkout my_
我正在尝试为我的模块找到一种在安装时创建 anchor 链接的方法。 我目前的策略是创建一个自定义菜单,类似于主菜单、次菜单等并位于其中。在此菜单中,我希望有一个或多个由我的模块定义的链接。然后我希望
我是一名优秀的程序员,十分优秀!