问题描述
我有一个接收道具并显示接收到的道具的组件。因此,我决定加载该页面网址而不接收任何支持,并且出现此错误:
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>
)
}
但是这些都不起作用。尝试了几个小时,尝试了不同的方法,但是都没有用,如果解决了怎么办?
解决方法
您需要一行以上的内容:
-
解构this.props.location.myInfo并添加可选值{}。
-
如果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>
)
}