Javascript React钩子使用上下文重新渲染组件
我正在使用全局钩子和useContext来存储已注册的用户信息。我不知道为什么useContext渲染我的组件两次,而第二次状态是未定义的。 提供者是全局的,在index.js中 有没有办法防止渲染组件两次 store.js:Javascript React钩子使用上下文重新渲染组件,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,我正在使用全局钩子和useContext来存储已注册的用户信息。我不知道为什么useContext渲染我的组件两次,而第二次状态是未定义的。 提供者是全局的,在index.js中 有没有办法防止渲染组件两次 store.js: import React, { createContext, useReducer } from 'react'; const initialState = { accessToken: '', expirationDate: '', fullName: '
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 };
import React,{createContext,useReducer}来自“React”;
常量初始状态={
accessToken:“”,
到期日期:“”,
全名:“”
};
const store=createContext(initialState);
const{Provider}=store;
const StateProvider=({children})=>{
const[state,dispatch]=useReducer((state,action)=>{
const{type,payload}=action;
开关(类型){
案例“登录”:
常数newState={
……国家,
…有效载荷
};
返回新闻状态;
违约:
抛出新错误();
}
},初始状态);
返回{children};
};
导出{store,StateProvider};
当我使用useContext(store)时,我得到以下结果:
不要默认为错误
始终在减速器中返回状态,而不是未定义。这是我看到的第一个问题
default:
throw new Error();
}
到
减速机执行了多少次?就是这样!reducer执行两次,对于令牌过期,谢谢!谢谢你!
default:
return state;
}