【问题标题】:How to redirect in react if prop is undefined如果 prop 未定义,如何在反应中重定向
【发布时间】:2021-02-19 15:22:59
【问题描述】:

我正在将另一个页面的道具传递到这个页面,它工作正常。所以我决定把接收页面的路由复制到另一个tab,所以就抛出了这个错误:

   TypeError: Cannot read property 'myData' of undefined

这是可以理解的,因为没有传递任何道具。我想要做的是路由到另一个页面,因为下面的代码行没有定义任何道具:

   componentDidMount() {
        this.props.location.state.myData === undefined && this.props.history.push('/');

        this.fetchData(data);
   }

但它不起作用,它给了我与上面相同的错误。我可能做错了什么以及如何解决这个问题?

【问题讨论】:

  • 你在使用 React 路由器吗?你能在路由规则而不是子组件中应用这个逻辑吗?
  • 瑞恩,你是什么意思?

标签: javascript reactjs routes react-router-dom


【解决方案1】:

在您的示例中,并不是说myData 未定义,而是说它无法读取未定义的属性 myData。即locationstate 属性未定义。

componentDidMount() {
  if (this.props.location.state === undefined) {
    this.props.history.push('/');
    return;
  }
  // else
}

【讨论】:

  • 如果location 不能保证是一个对象,你必须检查this.props.location && this.props.location.state === undefined
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2021-07-20
  • 2021-03-16
  • 2021-04-06
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多