使用 react-router-v4 对路由进行身份验证

IT技术 reactjs authentication redirect react-router
2021-04-03 02:52:47

我正在尝试Authentication为我的DashBoard. 但是函数本身没有被调用。谁能给我一些解决方案?我正在 ReactJs 中开发。

这是路线部分:

 <Router>
            <div>
              <Route exact path={"/"} component={Home} />
              <Route path={"/SignUp"} component={SignUp} />
              <Route path={"/SignIn"} component={SignIn} />
              <Route path={"/Dashboard"} component={Dashboard} onEnter={this.requireAuth} />
            </div>
          </Router>

这是功能:

  requireAuth (nextState, replace) {
    console.log("?????????????",this.state.getToken);
    if(!this.state.getToken) {
      replace({pathname: '/'});
    }
  }
1个回答

在 中react-router v4,您可以使用render proptoRoute和生命周期方法来替换onEnterreact-router v3 中现有功能。

有关更多详细信息,请参阅此答案:

react-router v4 中的 onEnter 属性

但是,由于您想要做的只是在 onEnter props中进行身份验证,因此您可以轻松创建一个执行此操作的 HOC

const RequireAuth = (Component) => { 

    return class App extends Component { 
    
        componentWillMount() { 
            const getToken = localStorage.getItem('token'); 
            if(!getToken) { 
               this.props.history.replace({pathname: '/'}); 
            } 
        } 
        render() { 
           return <Component {...this.props} /> 
        }
    } 

} 

export { RequireAuth }

并像使用它一样

<Route path={"/Dashboard"} component={RequireAuth(Dashboard)}/>

编辑:如果您需要进行网络调用以查找是否通过身份验证使用,您可以像这样编写 HOC

 const RequireAuth = (Component) => { 

    return class App extends Component { 
        state = {
            isAuthenticated: false,
            isLoading: true
        }
    
        componentDidMount() {
            AuthCall().then(() => {
                this.setState({isAuthenticated: true, isLoading: false});
            }).catch(() => {
                this.setState({isLoading: false});
            })
        } 
        render() { 
           const { isAuthenticated, isLoading } = this.state;
           if(isLoading) {
               return <div>Loading...</div>
           }
           if(!isAuthenticated) {
               return <Redirect to="/login" />
           }
           return <Component {...this.props} /> 
        }
    } 

} 

export { RequireAuth }

更新:

除了 HOC 之外,您还可以选择PrivateRoute像这样组件

const PrivateRoute = ({component: Component, isAuthenticated, isLoading, ...rest }) => { 
           if(isLoading) {
               return <div>Loading...</div>
           }
           if(!isAuthenticated) {
               return <Redirect to="/login" />
           }
           return <Component {...this.props} /> 
        }
    } 
} 

 export { PrivateRoute };

你可以像这样使用它

  class App extends Component { 
        state = {
            isAuthenticated: false,
            isLoading: true
        }
    
        componentDidMount() {
            AuthCall().then(() => {
                this.setState({isAuthenticated: true, isLoading: false});
            }).catch(() => {
                this.setState({isLoading: false});
            })
        } 
        render() { 
           <Router>
              <div>
                  <Route exact path={"/"} component={Home} />
                  <Route path={"/SignUp"} component={SignUp} />
                  <Route path={"/SignIn"} component={SignIn} />
                  <PrivateRoute path={"/Dashboard"} component={Dashboard} isAuthenticated={this.state.isAuthenticated} isLoading={this.isLoading}/>
               </div>
           </Router>
        }
    } 

   
@JL9 如果他们这样做,他们将进入视图,但如果他们向后端发送无效请求,服务器应以 401 响应,然后 ui 将重定向到登录
2021-05-29 02:52:47
有人可以不只是通过反应开发工具编辑反应状态来制作isAuthenticated: trueisLoading: false吗?然后他们就可以访问受保护的路线
2021-06-01 02:52:47