您尝试重定向到您当前使用AuthRoute的相同路线

时间:2017-12-02 01:00:44

标签: javascript reactjs redux react-router-v4

我有一个authroute,只需使用标记将用户重定向回登录页面,但我收到You tried to redirect to the same route的警告。

这是我的authroute组件

import React, { Component } from 'react'
import axios from 'axios'
import { withRouter } from 'react-router-dom'
import { getInfo } from '../../redux/user.redux'
import { connect } from 'react-redux'
import { Redirect } from 'react-router-dom'

@withRouter
@connect(state=>state.user,
    {getInfo}
)
class AuthRoute extends Component {
    componentDidMount() {

        const publicList = ['/login', '/register']
        const { pathname } = this.props.location

        //if user hit login or register route don't do anything
        if(publicList.indexOf(pathname)>-1){
            return null
        }
        this.props.getInfo()
    }

    render(){
        return <div>
            {this.props.redirectTo?<Redirect to={this.props.redirectTo} />:''}
        </div>
    }
}

export default AuthRoute

我的redux文件

import axios from 'axios'
import { getRedirectPath } from '../util'

const LOGIN_SUCESS = 'LOGIN_SUCESS'
const LOAD_DATA = 'LOAD_DATA'
const AUTH_FALSE = 'AUTH_FALSE'

const initState = {
    redirectTo: '',
    isAuth: false,
    msg: '',
    user: '',
    type: ''
}

//reducers
export function user(state=initState, action) {
    switch(action.type){
        case LOGIN_SUCESS:
            return {
                ...state,
                ...action.payload,
                msg: '',
                isAuth: true,
                redirectTo: getRedirectPath(action.payload)
            }
        case LOAD_DATA:
            return {...state, ...action.payload}
        case AUTH_FALSE:
            return {...state, redirectTo: '/login'}
        default:
            return state
    }
}

export function getInfo(){
    return dispatch=>{
        axios.get('/user/info')
            .then(res=>{
                if(res.status===200&&res.data.code===0){
                    dispatch({
                        type:LOGIN_SUCESS,
                        payload: res.data.data
                    })
                }else{
                    dispatch({type: AUTH_FALSE})
                }
            })
    }
}

使用带有cookie的getInfo方法调用请求,如果找不到用户,请将状态更改为具有redirectTo值。我做错了什么?我试图在componentDidMount中移动axios调用,并在回调中使用this.history.push(this.props.redirectTo),它没有那个错误,很奇怪。

0 个答案:

没有答案