【问题标题】:React hook useContext re-render componentReact hook useContext 重新渲染组件
【发布时间】:2020-06-12 17:37:14
【问题描述】:

我正在使用带有 useContext 的全局挂钩来存储已注册的用户信息。我不知道为什么 useContext 两次渲染我的组件,而第二次状态未定义。 Provider 是全局的,在 index.js 中

有什么办法可以防止两次渲染组件吗?

store.js:

import React, { createContext, useReducer } from 'react';

const initialState = {
  accessToken: '',
  expirationDate: '',
  fullName: ''
};
const store = createContext(initialState);
const { Provider } = store;

const StateProvider = ({ children }) => {
const [state, dispatch] = useReducer((state, action) => {
  const { type, payload } = action;

  switch (type) {
    case 'login':
      const newState = {
        ...state,
        ...payload
      };
      return newState;
    default:
      throw new Error();
    }
  }, initialState);

  return <Provider value={{ state, dispatch }}>{children}</Provider>;
};

export { store, StateProvider };

当我使用 useContext(store) 我得到这个结果:

useContext result

【问题讨论】:

  • 你的 reducer 执行了多少次?
  • 就是这样! reducer 执行两次,感谢令牌过期! ??????

标签: javascript reactjs react-hooks


【解决方案1】:

不要默认错误

总是在你的 reducer 中返回状态,而不是未定义的。这是我看到的第一个问题。

default:
  throw new Error();
}

default:
  return state;
}

【讨论】:

  • 谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-14
  • 1970-01-01
  • 2019-10-05
  • 2021-06-19
  • 2018-04-22
  • 1970-01-01
相关资源
最近更新 更多