【发布时间】: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) 我得到这个结果:
【问题讨论】:
-
你的 reducer 执行了多少次?
-
就是这样! reducer 执行两次,感谢令牌过期! ??????
标签: javascript reactjs react-hooks