使用 react-router-v4 对路由进行身份验证 [英] Performing Authentication on Routes with react-router-v4

查看:38
本文介绍了使用 react-router-v4 对路由进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写 Authentication 检查我的 DashBoard.但是函数本身没有被调用.谁能给我一些解决方案?我正在使用 ReactJs 进行开发.

这是路线部分:

 <路由器><div><路由精确路径={"/"} component={Home}/><路由路径={"/SignUp"} 组件={SignUp}/><路由路径={"/SignIn"} 组件={SignIn}/><Route path={"/Dashboard"} component={Dashboard} onEnter={this.requireAuth}/>

</路由器>

这是函数:

 requireAuth (nextState, replace) {console.log("?????????????",this.state.getToken);如果(!this.state.getToken){替换({路径名:'/'});}}

解决方案

react-router v4中,你可以利用render propRoute 以及生命周期方法来替换 react-router v3 中存在的 onEnter 功能.

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

react-router v4 中的 onEnter prop

然而,由于您想要做的只是在 onEnter 属性中进行身份验证,您可以轻松地创建一个 HOC 来执行此操作

const RequireAuth = (Component) =>{返回类 App 扩展组件 {componentWillMount() {const getToken = localStorage.getItem('token');如果(!getToken){this.props.history.replace({pathname: '/'});}}使成为() {return <Component {...this.props}/>}}}导出 { RequireAuth }

并像使用它一样

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

 const RequireAuth = (Component) =>{返回类 App 扩展组件 {状态 = {isAuthenticated: 假,isLoading: 真}componentDidMount() {AuthCall().then(() => {this.setState({isAuthenticated: true, isLoading: false});}).catch(() => {this.setState({isLoading: false});})}使成为() {const { isAuthenticated, isLoading } = this.state;如果(正在加载){返回<div>加载中...</div>}如果(!isAuthenticated){return 

更新:

除了 HOC,您还可以使用 PrivateRoute 组件,如

const PrivateRoute = ({component: Component, isAuthenticated, isLoading, ...rest }) =>{如果(正在加载){返回<div>加载中...</div>}如果(!isAuthenticated){return 

你可以像这样使用它

 class App extends Component {状态 = {isAuthenticated: 假,isLoading: 真}componentDidMount() {AuthCall().then(() => {this.setState({isAuthenticated: true, isLoading: false});}).catch(() => {this.setState({isLoading: false});})}使成为() {<路由器><div><路由精确路径={"/"} component={Home}/><路由路径={"/SignUp"}组件={SignUp}/><路由路径={"/SignIn"}组件={SignIn}/><PrivateRoute path={"/Dashboard"} component={Dashboard} isAuthenticated={this.state.isAuthenticated} isLoading={this.isLoading}/>

</路由器>}}

I'm trying to write Authentication checking for my DashBoard. But the function itself is not getting called. Can anyone give me some solution for this? I'm developing in ReactJs.

This is the Route part :

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

This is the function :

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

解决方案

In react-router v4, you can make use of render prop to Route along with the lifecycle methods to replace the onEnter functionality existing in react-router v3.

See this answer for more details:

onEnter prop in react-router v4

However since all you want to do is authentication in the onEnter prop, you could easily create a HOC that does that

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 }

and use it like

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

Edit: In case you need to make a network call to find if the use if authenticated of not, you would write the HOC like

 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 }

Update:

In addition to the HOC, you can also go for the PrivateRoute component like

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

and you can use it like

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

   

这篇关于使用 react-router-v4 对路由进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆