简体   繁体   English

在React中以更高阶组件触发异步调用

[英]firing async call in higher order component in react

I have this HOC component where it check if a user has privilege to be redirect to certain route, but I don't know how and where to fire async call. 我有这个HOC组件,它在其中检查用户是否有权重定向到某些路由,但是我不知道如何以及在哪里触发异步调用。

export default function CheckPermission(EnhancedComponent) {
  return class Redirect extends Component {

    render() {

      const special_member_token = '3453564' //hardcoded for temp

      const on_special_member_route = this.props.location.pathname.includes('special_member')

      if (getUserRole() === 'special_member' && !on_applied_route) {

        return <Redirect to={`/dashboard/special_member/${special_member_token}`} />
      }

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

Call the api in render is an anti pattern, should I do it in componentDidMount ? 在render中调用api是一种反模式,我应该在componentDidMount吗? But the render has already been trigger once if I call in componentDidMount , I have to avoid the wrapped component being render at all if the redirect have to happens. 但是,如果我在componentDidMount调用,则渲染已经被触发一次,如果必须进行重定向,则必须避免打包的组件被渲染。

You need to fire async call in two methods: 您需要通过两种方法来触发异步调用:

1) componentWillMount - component not rendered yet. 1) componentWillMount组件尚未渲染。 2) componentWillUpdate - maybe your app url changed and this component receive new props and will be update and need to check user priveleges 2) componentWillUpdate也许您的应用网址已更改,并且此组件收到新的道具,并且将被更新,并且需要检查用户权限

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

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