【问题标题】:Unable to update a particular state using React Reducer无法使用 React Reducer 更新特定状态
【发布时间】:2020-06-30 18:05:04
【问题描述】:

我在我的应用程序上使用 React Context。

这是在我的 Provider 文件中:


// Initial State
const initialState = {
  user: [],
  monitors: '',
  loading: true,
  isAuthenticated: false,
};

  function getMonitors(username) {
    axios
      .get(`/api/users/usermonitors/?user=${username}`)
      .then((res) => {
        dispatch({
          type: 'GET_MONITORS',
          payload: res.data.monitors,
        });
        console.log(res.data.monitors); // This returns expected response
      })
      .catch((err) => console.log(err));
  }

这在 Reducer 文件中:

case 'GET_MONITORS':
      return {
        ...state,
        monitors: action.payload,
   };

我在我的视图文件中调用它如下:

useEffect(() => {
    getMonitors(user.email);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

问题是 Reducer 没有更新状态,我不明白为什么。所有其他 Provider 操作都被 Reducer 成功更新为 state,但不是这个。

并且,在 Dispatch 之后的 Provider 文件中的 console.log(res.data.monitors); 返回预期的响应。

我在这里缺少什么?

【问题讨论】:

    标签: javascript reactjs react-context


    【解决方案1】:

    代码运行正常,并且也在更新状态。问题是,我在 Chrome 上检查 React Devtools 的状态,但它没有显示更新的状态。

    然后我在其中一个视图文件中控制台记录该特定状态,它消除了我的疑问。

    【讨论】:

      猜你喜欢
      • 2020-04-07
      • 2020-08-09
      • 2021-01-08
      • 1970-01-01
      • 1970-01-01
      • 2020-04-14
      • 2019-10-17
      • 1970-01-01
      • 2017-08-08
      相关资源
      最近更新 更多