简体   繁体   English

当消费者调用时,作为上下文值传递的函数无法访问更新的组件状态

[英]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.我想通了这个问题,其实,我是用debounceConsumeruseCallback ,我错过了传球providerFunction作为一个依赖。

After adding the dependency, it worked!添加依赖项后,它起作用了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在子组件中传递和调用的函数无权访问父状态值 - Function passed and invoked in child component doesn't have access to parent state value 当提供程序组件父状态更改时,为什么无法更新子组件中的值(使用react上下文)? - Why can't update a value in a child component (with react context) when a provider component parent state change? 选择值状态更新时未调用componentDidMount - componentDidMount is not called when select value state updated 无法访问 React js 组件的传递值 - Can't access React js component's passed down value 为什么在调用函数时无法正确传递参数? - Why the parameter can't be passed properly when function called? 当子组件作为属性传递时,react状态不会更新/传递给子组件 - react state is not updated/passed to child component when child component is passed as a property 无法使用附加元素访问更新的 state - can't access to updated state with appanded element 如何访问已调用setState的函数体中的更新状态? - How to access the updated state in the body of a function that has already called setState? setState()之后,更新后的状态不作为道具传递给组件 - Updated state is not passed as props to component after setState() 通过 prop 传递给子组件的 Function 在调用时不是 function - Function passed via a prop to child component is not a function when called
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM