Reactjs 对授权用户(受保护的路由)的检查作出反应

Reactjs 对授权用户(受保护的路由)的检查作出反应,reactjs,react-router-v4,higher-order-components,Reactjs,React Router V4,Higher Order Components,我正在尝试构建一个用于保护路由的高阶组件。它将检查(通过网络调用,而不是从缓存)当前用户,如果找不到,将重定向到/login 有什么想法吗?首先要了解它是如何工作的。我将尝试使用伪代码来回答这个问题 HOC.jsx export default (Component) => class HOC extends React.Component { constructor(){ super() this.state = { waiting: true,

我正在尝试构建一个用于保护路由的高阶组件。它将检查(通过网络调用,而不是从缓存)当前用户,如果找不到,将重定向到/login

有什么想法吗?

首先要了解它是如何工作的。我将尝试使用伪代码来回答这个问题

HOC.jsx

export default (Component) => class HOC extends React.Component {
  constructor(){
    super()
    this.state = {
      waiting: true,
    }
  }

  componentDidMount() {
    this.props.actions.validateUser() // your network call to validate user
    .then(() => {
      // do your stuff
      this.setState({
        waiting: false,
      })
    })
    .catch(() => {
      // handle redirect using react-router
    })
  }

  render() {
    if(this.state.waiting) {
      // Add a loader here
      return <h1>Loading...</h1>
    }

    return <Component {...this.props} />

  }

}
export default(Component)=>class.Component{
构造函数(){
超级()
此.state={
等待:是的,
}
}
componentDidMount(){
this.props.actions.validateUser()//验证用户身份的网络调用
.然后(()=>{
//做你的事
这是我的国家({
等待:错,
})
})
.catch(()=>{
//使用react路由器处理重定向
})
}
render(){
if(本状态等待){
//在这里添加一个加载器
返回加载。。。
}
返回
}
}
组件.jsx

import HOC from './HOC.jsx'

class Comp extends React.Component {
  render() {
    return <h1>I'm a valid user</h1>
  }
}

export default HOC(Comp)
import-HOC from./HOC.jsx'
类Comp.Component{
render(){
return我是有效用户
}
}
导出默认HOC(Comp)
当任何组件使用HOC时,网络调用将在装载时执行(也可以移动到
componentWillMount
),并根据响应呈现组件

希望这有帮助

可能重复的