【问题标题】:I am using ContextAPI in a React Application but I am not able access the states with correct values in componentsI am using ContextAPI in a React Application but I am not able access the states with correct values in components
【发布时间】:2022-12-01 20:56:32
【问题描述】:
useEffect(() => {
    getQuestionDetails();
    getAnswers();
}, []);

I am using the above useEffect hook in a react functional component, I am calling to async functions which fetch data using axios from server. I use some state values in context API as payload in the http requests of axios . for the first render I am getting the values of states from context properly but after that values are not proper. not only the functions inside useEffect but one more function outside useEffect also not able to get corrects state value

This is the first ever render where some payload values are taken from context API:

This is after I reloaded the same page, I am not getting values from context:

I am trying to get the correct values of states from context API for every render, but I am getting the correct values only for the first ever render but after that when I reload the page initial values which were assigned while creating states are coming.

【问题讨论】:

    标签: reactjs react-hooks frontend react-context


    【解决方案1】:
    useEffect(() => {
        getQuestionDetails();
        getAnswers();
    });
    

    Use the hook like that. The reason is the '[]' in the hook parameters. It sajs that reinvoke the hook only if [] is different than [].

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 2022-12-02
      • 2022-12-27
      • 2022-11-20
      • 2022-12-27
      • 1970-01-01
      • 2022-12-27
      • 2022-12-19
      • 2022-12-01
      相关资源
      最近更新 更多