What component lifecycle to use to do something before render()?

前端 未结 4 455
悲&欢浪女
悲&欢浪女 2020-12-04 02:48

I need to check whether some props (from redux store) is an empty object or not. If it is empty, I want the page to redirect to another page and not bother to call ren

4条回答
  •  盖世英雄少女心
    2020-12-04 03:21

    history.push() is a side effect that won't prevent the component to be initially rendered, so it belongs to componentDidMount.

    Since the result depends on props, the check could go to getDerivedStateFromProps to provide redirect flag in a component with local state. In a component that is connected to Redux it can be performed in mapStateToProps:

    connect(({ someObj }) => ({ redirect: !Object.keys(someObj) }))(...)
    

    The component shouldn't be rendered if it will redirect:

    componentDidMount() {
      if (this.props.redirect)
        this.props.history.push("/some-other-route");
    }
    
    render() {
       return !this.props.redirect && (
         ...
       );
    }
    

    As another answer correctly mentions, component is a declarative alternative to calling history.push() directly.

提交回复
热议问题