【问题标题】:react js Axios request failed: TypeError: Cannot read property 'token' of undefined?react js Axios请求失败:TypeError:无法读取未定义的属性'token'?
【发布时间】:2020-11-28 10:33:42
【问题描述】:

如果我尝试使用此令牌授权它,我已经使用 react redux 从登录中获取令牌。错误是显示Axios request failed: TypeError: Cannot read property 'token' of undefined 我想用令牌授权它。令牌存储在本地存储中,但是当我使用(Token ${props.token} 时它无法授权它如果我尝试这种方式(Token 5302f4340a76cd80a855286c6d9e0e48d2f519cb} 那么我的 AritcleList.js 已授权它

这里是 react-redux 认证

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;
        }
    }

articleList.js

import React, { useState, useEffect } from 'react';
    import { Container, Row, Col } from 'react-bootstrap';
    import Card from '../components/Card'
    import FullPageLoader from "../components/FullPageLoader";
    import axios from 'axios';
    import { connect } from 'react-redux'

    const NewsList = () => {
        const [items, setItems] = useState([])
        const [isLoading, setLoading] = useState(true)
        const [isAuthenticated, setAuth] = useState(true); //i don't know how to authenticate it when i also login

        useEffect((props) => {
            const fetchItems = async () => {
                try {
const config = {
                    headers: {
                        'Content-Type': 'application/json',
                        Authorization: `Token ${props.token}`
                    }
                }
                    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]);
        return (
            <Container className="mt-5">
                < div className="bread-header" >
                    <h5>Dashboard</h5>
                </div >
                <hr />
                <Row>
                    <Col sm={8}>
                        {
                            isLoading ? <FullPageLoader /> :
                                <div>
                                    {itemData.map((item, index) => (
                                        <Card key={index} item={item} isAuthenticated={isAuthenticated} ></Card>
                                    ))}
                                </div>
                        }
                    </Col>
                </Row>
            </Container >
        )
    }

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

【问题讨论】:

    标签: javascript reactjs react-redux axios


    【解决方案1】:

    useEffect 不接受任何参数,因此props 将始终未定义:

    useEffect((props) => {
    

    我猜你想这样做:

    const NewsList = (props) => {
        // ...
        useEffect(() => {
           // ...
        }, [items]);
        // ...
     }
    
    const mapStateToProps = (state) => {
        return {
            isAuthenticated: !!state.auth.token,
            token: state.auth.token
        }
    }
    export default connect(mapStateToProps)(NewsList)
    

    【讨论】:

    • 是的,使用了这个代码,但同样的 error? Axios request failed: TypeError: Cannot read property 'token' of undefined 错误显示在控制台中
    猜你喜欢
    • 2021-02-18
    • 2021-12-10
    • 2022-11-17
    • 2020-12-24
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2021-07-25
    相关资源
    最近更新 更多