[英]How to pass dependency in useEffect hook inside Context
I have an useEffect
hook inside Context.我在 Context 中有一个
useEffect
钩子。 Also, i have two functional component, from one of them, i am calling context like const context = useContext(ApiContext);
此外,我有两个功能组件,其中之一,我调用上下文,如
const context = useContext(ApiContext);
but at the same time, from the same component, need to pass dependency of useEffect
as well so that useEffect
code should execute only if the dependency changes, here for example.."Name" and "Range".但同时,来自同一个组件,也需要传递
useEffect
依赖,这样useEffect
代码应该只在依赖改变时才执行,例如..“Name”和“Range”。 Below is my context code下面是我的上下文代码
import React, { useState, useEffect } from 'react';
export const ApiContext = React.createContext();
const Context = props => {
const [articles, setArticles] = useState([]);
useEffect(() => {
console.log('rendered');
setArticles(['Article One', 'Article Two', '...ect']);
}, [props.Name, props.Range]);
return <ApiContext.Provider value={articles}>{props.children}</ApiContext.Provider>;
};
export default Context;
Here is codeSandBox exmaple: https://codesandbox.io/s/route-rerender-api-fix-q9tu2这是 codeSandBox 示例: https ://codesandbox.io/s/route-rerender-api-fix-q9tu2
How to passs props.Name
and props.Range
from from my functional component?如何从我的功能组件传递
props.Name
和props.Range
?
You can do like this to spread all the props from parent - class component你可以这样做来传播父类组件的所有道具
<Context {...this.props} >....your components...</Context>,
or like for specific或喜欢特定的
<Context name='test'>... your components ....</Context>
and you can access like in the context你可以在上下文中访问
useEffect(() => {
console.log("rendered with props", props.name);
setArticles(['Article One', 'Article Two', '...ect']);
}, [props.name]);
working codesandbox - check the console工作代码和框- 检查控制台
passing input from child component - codesandbox从子组件传递输入 -代码沙盒
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.