javascript - 为什么在通过 useContect(context) 调度时不会记录保存用户身份验证令牌的变量?
问题描述
我不确定为什么console.log(state);
不显示我的身份验证令牌。我相信我已经正确设置了商店和减速器,但我猜不是。我无法发现我在这里做错了什么。
我的目标是在整个应用程序中在全局级别上访问身份验证令牌,但首先我需要通过dispatch({})
.
我该如何纠正这个问题?
这是我的小部件组件:
const [state, dispatch] = useContext(Context);
// the data variable doesn't need to be shown as it has nothing to do with issue I'm facing, just FYI.
axios.post('http://mySite.test/api/register', data)
.then(resp => {
console.log(resp.data.data.token); // token logs successfully
dispatch({type: 'GET_TOKEN', payload: resp.data.data.token});
console.log(state); // logging {token: ""}
}).catch(error => {
console.log(error);
});
这是 Reducer.js:
const Reducer = (state, action) => {
switch (action.type) {
case 'GET_TOKEN':
return {
...state,
token: action.payload
};
default:
return state;
}
};
export default Reducer;
这是 Store.js:
import React, {createContext, useReducer} from "react";
import Reducer from '../Reducer/Reducer'
const initialState = {
token: ''
};
const Store = ({children}) => {
const [state, dispatch] = useReducer(Reducer, initialState);
return (
<Context.Provider value={[state, dispatch]}>
{children}
</Context.Provider>
)
};
export const Context = createContext(initialState);
export default Store;
解决方案
推荐阅读
- c# - 图像分类中 Ml.net 中的异常
- webpack - 即使我在 webpack 中定位它,也找不到带有本机扩展的 react-native-web 模块
- javascript - Vue分隔符不在属性中工作,但在元素中工作
- php - Nginx 没有正确加载 JS、CSS
- git - git 开关保留被忽略的文件夹
- python - 你如何“连接”这个源代码和我的 tkinter python
- docker - 如何在不手动运行 dbt deps 的情况下配置 DBT 依赖项?
- python - 为什么在这个 for 循环中打印 3?
- python - pygame中的随机系统运动
- vb.net - 在文本框中更改特定数字范围的字体颜色