如果在react

问题描述

我有一个接收道具并显示接收到的道具的组件。因此,我决定加载该页面网址而不接收任何支持,并且出现此错误

   TypeError: Cannot destructure property 'myImage' of '(intermediate value)(intermediate value)(intermediate value)' as it is undefined.

因此,如果未收到道具(如果未定义),我尝试使用以下代码重定向页面

    componentDidMount(){
        if(this.props.location.myInfo === undefined){
            this.props.history.push('/');
            return;
        }
        this.setState({ name: this.props.location.myInfo });
    }
   render(){
      const { myImage,myName,myJobType,myPrice } = this.props.location.myInfo ? this.props.location.myInfo : this.props.history.push('/');
      return(
         <div>
            ...
         </div>
      )
   }

但是这些都不起作用。尝试了几个小时,尝试了不同的方法,但是都没有用,如果解决了怎么办?

解决方法

您需要一行以上的内容:

  1. 解构this.props.location.myInfo并添加可选值{}。

  2. 如果this.props.location.myInfo未定义,请调用this.props.history.push。

render(){
      const { myImage,myName,myJobType,myPrice } = this.props.location.myInfo || {};
      if(!this.props.location.myInfo) {
          this.props.history.push('/')
      }
      return(
         <div>
            //...
         </div>
      )
   }


componentDidMount() {
  if(!this.props.location.myInfo) {
     this.props.history.push('/')
  }
}

render(){
  const { myImage,myPrice } = this.props.location.myInfo || {};   
  return
  (
     <div>
        //...
     </div>
  )
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...