higher order function render twice causing child c

2019-08-16 04:43发布

问题:

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