如果没有在反应中定义道具,如何重定向到另一个页面

How to redirect to another page if prop is not defined in react

我有一个组件可以接收道具并显示收到的道具。所以我决定加载这个页面 url 而没有收到道具,我得到这个错误:

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

但是 none 这些作品。已经尝试了几个小时,尝试了不同的方法,但 none 正在工作,如果修复了,我该如何获取?

您需要不止一行来执行此操作:

  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, myName, myJobType, myPrice } = this.props.location.myInfo || {};   
  return
  (
     <div>
        //...
     </div>
  )
}