higher order function render twice causing child component to be triggered

北城余情 提交于 2019-12-24 14:09:48

问题


I have a protected route, implemented using higher order component, but in my App.js which is the child component, trigger its componentDidMount method, I wonder why is it so..

Route.js

...
<BrowserRouter>
  <Switch>
    <Route exact path='/app' component={CheckPermission(App)} />
    <Route exact path='/app/login' component={Login} />
  </Switch>
</BrowserRouter>
...

Auth.js

export default function CheckPermission(EnhancedComponent) {
  class Auth extends Component {
    static contextTypes = {
      router: PropTypes.object
    }

    componentWillMount() {
      if (!this.props.isAuth) {
        this.context.router.history.replace(`/login`)
      }
    }

    componentWillUpdate() {
      if (!this.props.isAuth) {
        this.context.router.history.replace(`/login`)
      }
    }

    render() {
      return <EnhancedComponent { ...this.props } />
    }
  }

  return connect()(Auth)
}

App.js

class App extends Component {
  componentDidMount(){
    console.log('test') //why is this trigger??
  }
  render() {
    return <h1>App</h1>
  }
}

If I have API call in App.js's componentDidMount, it will cause unwanted call, I thought componentWillMount of the Auth.js prevent render to trigger already? I see in my browser, the redirect by Auth.js just worked.


回答1:


There is no guarantee that the replace method in componentWillMount will redirect before the render method fired.

You might want to refactor your Auth.js code to something like this.

export default function CheckPermission(EnhancedComponent) {
  class Auth extends Component {
    render() {
      // Note that we return a <Redirect /> component here early for not giving <EnhancedComponent /> any chance to render itself.
      if (!this.props.isAuth) {
        return <Redirect to="/login" />
      }

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

  return connect()(Auth)
}


来源:https://stackoverflow.com/questions/49477117/higher-order-function-render-twice-causing-child-component-to-be-triggered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!