[英]Function passed as context value can't access updated component state when called by a consumer
I am passing a function to as value to the Context Provider
and on calling that function from the consumer, I'm getting the older state.我正在将一个函数作为值传递给
Context Provider
并且在从使用者调用该函数时,我得到了较旧的状态。
Provider.jsx Provider.jsx
const MyContext = createContext();
const Provider=()=>{
const [someState, setSomeState] = useState();
const providerFunction=()=>{
// accessing someState
}
<MyContext.Provider value={{providerFunction}}>
<ConsumerComponent/>
</MyContext.Provider>
Comsumer.jsx消费者.jsx
const {providerFunction} = useContext(MyContext);
On calling providerFunction
from Consumer.jsx
, providerFunction in Provider.jsx is called but someState
is not getting the updated value, it is printing the initial value assigned to it.在从
Consumer.jsx
调用providerFunction
时,Provider.jsx 中的 providerFunction 被调用,但someState
没有获得更新的值,它正在打印分配给它的初始值。
I'm unable to figure out the reason for this.我无法弄清楚这是什么原因。 Any help is appreciated.
任何帮助表示赞赏。
I figured out the issue, actually, I was using debounce
in Consumer
and in useCallback
, I missed passing providerFunction
as a dependency.我想通了这个问题,其实,我是用
debounce
在Consumer
和useCallback
,我错过了传球providerFunction
作为一个依赖。
After adding the dependency, it worked!添加依赖项后,它起作用了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.