首页 > 解决方案 > 为什么在通过 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;

标签: javascriptreactjsdebuggingreact-hooks

解决方案


推荐阅读