简体   繁体   English

带有 Redux 的专用路由

[英]Private Route with Redux

I am trying to create a private route which checks user authentication.我正在尝试创建一个检查用户身份验证的私有路由。 But the Private route renders before data from redux Is updated.但是私有路由在 redux 的数据更新之前呈现。 The component has like isauthenticated variable which eventually updates to true but the component renders first before it gets updated.该组件具有类似 isauthenticated 变量,该变量最终更新为 true,但组件在更新之前先呈现。 As the redux has its value as false at 1st render.由于 redux 在第一次渲染时其值为 false。

import React, { Component } from 'react'
import {connect} from 'react-redux'
import {Route, Redirect } from 'react-router-dom'

const PrivateRoute = ({component: Component, isAuthenticated, ...rest}) =>{
    return(
        <Route {...rest} render={
            (props) => {
                if(isAuthenticated) { 
                    return <Component {...props}/>
                }else{
                    return <Redirect to="/login"/>
                }

            }
        }/>
    )
}

const mapStateToProps = state =>{
    return{
        isAuthenticated: state.token !== null
    }
}

export default connect(mapStateToProps, null)(PrivateRoute)

You can wrap your router inside an auth-is-loaded component:您可以将路由器包装在auth-is-loaded组件中:

import React from "react";
import { useSelector } from "react-redux";
import { isLoaded } from "react-redux-firebase";

export default function AuthIsLoaded({ children }) {
  const auth = useSelector(state => state.firebase.auth);

  if (isLoaded(auth)) return children;
  return <div>Loading...</div>;
}

So App.js will be like this:所以 App.js 会是这样的:

  return (
    <Provider store={store}>
        <BrowserRouter>
          <AuthIsLoaded>
            <NavBar />
              <Switch>
                <Route exact path="/" component={Home} />
                <PrivateRoute path="/about" component={About} />
                <PrivateRoute path="/profile" component={Profile} />
                <Route path="/login" component={Login} />
                <Route path="/signup" component={SignUp} />
                <Route path="/logout" component={Logout} />
              </Switch>
            </AuthIsLoaded>
        </BrowserRouter>
    </Provider>
  );

So after auth loaded your switch will be rendered PrivateRoutes wont get isAuthenticated before redux load it.因此,在加载身份验证后,您的交换机将呈现 PrivateRoutes 在 redux 加载之前不会获得 isAuthenticated 。

Sorry about some extra code, I copied from my app, but you should get the idea.对不起,我从我的应用程序中复制了一些额外的代码,但你应该明白了。

simply add option {pure:false} to connect.只需添加选项 {pure:false} 即可连接。 and you should be good to go.你应该对go很好。

export default connect(mapStateToProps, null, null, {
  pure: false,
})(PrivateRoute);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM