简体   繁体   中英

higher order function render twice causing child component to be triggered

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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