首页 > 解决方案 > isAuthenticated 是未定义的反应js吗?

问题描述

当我运行此代码时,isAuthenticated 未定义。如何使用 isAuthenticated 和mapStateProps. 如果我像这样使用 Token `(Token '5302f4340a76cd80a855286c6d9e0e48d2f519cb'} 那么它工作正常但我想用 props.isAuthenticated 授权它有人知道我该如何解决这个问题吗?

authAction.js

import axios from 'axios';
    import * as actionTypes from './actionTypes';

    export const authStart = () => {
        return {
            type: actionTypes.AUTH_START
        }
    }

    export const authSuccess = token => {
        return {
            type: actionTypes.AUTH_SUCCESS,
            token: token
        }
    }

    export const authFail = error => {
        return {
            type: actionTypes.AUTH_FAIL,
            error: error
        }
    }

    export const logout = () => {
        localStorage.removeItem('token');
        return {
            type: actionTypes.AUTH_LOGOUT
        };
    }



    export const authLogin = (userData) => {
        return dispatch => {
            dispatch(authStart());
            axios.post('http://localhost:8000/rest-auth/login/', userData)
                .then(res => {
                    const token = res.data.key;
                    localStorage.setItem('token', token);
                    dispatch(authSuccess(token));
                })
                .catch(err => {
                    dispatch(authFail(err))
                })
        }
    }

authReducer.js

import * as actionTypes from '../actions/actionTypes';
    import { updateObject } from '../utility';

    const initialState = {
        isAuthenticated: null,
        token: null,
        error: null,
        loading: false
    }

    const authStart = (state, action) => {
        return updateObject(state, {
            isAuthenticated: false,
            error: null,
            loading: true
        });
    }

    const authSuccess = (state, action) => {
        return updateObject(state, {
            isAuthenticated: true,
            token: action.token,
            error: null,
            loading: false
        });
    }

    const authFail = (state, action) => {
        return updateObject(state, {
            error: action.error,
            loading: false
        });
    }

    const authLogout = (state, action) => {
        return updateObject(state, {
            token: null
        });
    }

    export default function (state = initialState, action) {
        switch (action.type) {
            case actionTypes.AUTH_START: return authStart(state, action);
            case actionTypes.AUTH_SUCCESS: return authSuccess(state, action);
            case actionTypes.AUTH_FAIL: return authFail(state, action);
            case actionTypes.AUTH_LOGOUT: return authLogout(state, action);
            default:
                return state;
        }
    }

index.js

import { combineReducers } from 'redux';
import auth from './authReducer'

export default combineReducers({
    auth: auth
});

文章List.js

const NewsList = (props) => {
    // ...
   const fetchItems = async () => {
                try {
                    const config = {
                    headers: {
                        'Content-Type': 'application/json',
                        Authorization: `Token ${props.isAuthenticated}`
                    }
                }
                    const res = await axios.get(`${process.env.REACT_APP_API_URL}/api/`, config);
                    setItems(res.data)
                    setLoading(false);
                }
                catch (err) {
                    console.log(` Axios request failed: ${err}`);
                }
            }
            fetchItems()
        })
        }, [items]);
    // ...
 }

const mapStateToProps = (state) => {
    return {
        isAuthenticated: state.auth.token
    }
}
export default connect(mapStateToProps)(NewsList)

标签: reactjsreact-redux

解决方案


你需要调试你的代码。从连接点开始:输出告诉你props.isAuthenticatedundefined. 你从state.auth.tokenin传入这个mapStateToProps()

const mapStateToProps = (state) => {
    return {
        isAuthenticated: state.auth.token
    }
}

所以state.auth.token也必须是未定义的。从你向我展示的内容中,我能得到的就是这些。您将需要进一步调试以找出原因。你可以使用 React 开发工具来检查组件的 props。您可以使用 Redux Dev Tools 来检查和操作 redux 状态。检查auth.token状态的值。查看它应该设置的位置,并找出它没有设置为有效值的原因。

请务必查看本文以获取有关如何调试代码的提示。


推荐阅读