[英]How to redirect to another page if prop is not defined in react
I have a component that receives props and displays the received props.我有一个接收道具并显示接收到的道具的组件。 So I decided to load this page url without receiving a prop and I get this error:所以我决定在没有收到道具的情况下加载这个页面 url,我收到了这个错误:
TypeError: Cannot destructure property 'myImage' of '(intermediate value)(intermediate value)(intermediate value)' as it is undefined.
So I tried to redirect the page if the props is not received (if it is undefined) with the following lines of code:因此,如果未收到道具(如果未定义),我尝试使用以下代码行重定向页面:
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>
)
}
But none of these works.但这些都不起作用。 Been on it for hours trying different methods but none is working, how can I get if fixed?已经使用了几个小时尝试不同的方法,但都没有奏效,如果修复了我怎么办?
You need more than one line to do this:你需要不止一行来做到这一点:
Destructure this.props.location.myInfo and add optional value {}.解构 this.props.location.myInfo 并添加可选值 {}。
Call this.props.history.push if this.props.location.myInfo is undefined.如果 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>
)
}
or或者
componentDidMount() {
if(!this.props.location.myInfo) {
this.props.history.push('/')
}
}
render(){
const { myImage, myName, myJobType, myPrice } = this.props.location.myInfo || {};
return
(
<div>
//...
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.