【问题标题】:React component lifecycles still run after redirectReact 组件生命周期在重定向后仍然运行
【发布时间】:2019-03-23 06:57:56
【问题描述】:

在我的组件中,我想检查用户是否已登录,如果没有,则重定向到登录页面。目前我在 componentWillMount 中进行检查和重定向。

  public componentWillMount() {
    if(this.props.master === null) {
      this.props.history.push('./login');
    }
  }

但是,即使重定向确实发生了,render() 和 componentDidMount() 仍然运行,这会使我的代码崩溃,因为在那里我假设 master 不为空。

【问题讨论】:

    标签: reactjs redirect react-router


    【解决方案1】:

    考虑使用这样的机制:

    When user is not logged in redirect to login. Reactjs

    将用户重定向到路由器上的登录页面,而不是受限组件。

    请注意componentWillMount,因为它将在未来的版本中弃用。 https://reactjs.org/docs/react-component.html#unsafe_componentwillmount

    【讨论】:

    • 啊,所以您将组件包装在另一个组件中,该组件决定显示它。好的解决方案,我会尝试它,如果它有效,则会将此答案标记为已接受。很遗憾,react-router 示例没有任何随附的解释。
    • 抱歉回复晚了,但这种方法效果很好,实现很干净。
    【解决方案2】:

    试试:

    如果 shouldComponentUpdate() 返回 false,则不会调用 componentWillUpdate()render()componentDidUpdate()

    shouldComponentUpdate() {
      if (this.props.master == null) return false
    }
    

    答案来自:Stop rendering of a component after componentDidMount()

    【讨论】:

    • 不会阻止初始渲染。
    猜你喜欢
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多