首页 > 解决方案 > React 中的重定向路由

问题描述

我写了一个组件,它应该将unlogged用户重定向到主页“/”。

问题是:

我不知道为什么这个组件会重定向用户,无论他们是否登录......

import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { connect } from 'react-redux'
  
const ProtectedRoute = ({ component: Component, ...rest }) => {
    console.log("ha")
    return (
        <Route {...rest} render={(props) => (
            props.auth ?
            <Component {...props} /> :
            <Redirect to="/" />
        )} />
    );
}
 
const mapStateToProps = state => {
    console.log(state.firebase.auth.uid,"PR")
    return{
        auth: state.firebase.auth.uid
    }
}
 
export default connect(mapStateToProps)(ProtectedRoute)

在控制台我得到这个: 在此处输入图像描述

如果我理解得很好,那么uid存在于渲染时刻......:v

标签: reactjs

解决方案


好的问题在

<Route {...rest} render={(props) => (
    props.auth ?
    <Component {...props} /> :
    <Redirect to="/" />
)}/>

这个props没有auth

const ProtectedRoute = ({ component: Component, auth, ...rest }) => {
    console.log("ha")
    return (
        <Route {...rest} render={(props) => (
            auth ?
            <Component {...props} /> :
            <Redirect to="/" />
        )} />
    );
}

像上面那样做


推荐阅读