Javascript 如果react中未定义prop,如何重定向到另一个页面
我有一个组件,它接收道具并显示收到的道具。因此,我决定在不接收道具的情况下加载此页面url,并出现以下错误:Javascript 如果react中未定义prop,如何重定向到另一个页面,javascript,reactjs,react-props,destructuring,Javascript,Reactjs,React Props,Destructuring,我有一个组件,它接收道具并显示收到的道具。因此,我决定在不接收道具的情况下加载此页面url,并出现以下错误: TypeError: Cannot destructure property 'myImage' of '(intermediate value)(intermediate value)(intermediate value)' as it is undefined. 因此,如果没有收到道具(如果未定义),我尝试使用以下代码行重定向页面: componentDidMoun
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>
)
}
componentDidMount(){
if(this.props.location.myInfo==未定义){
this.props.history.push('/');
返回;
}
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('/');
返回(
...
)
}
但这些都不管用。几个小时来,我一直在尝试不同的方法,但都不起作用,如果修复了,我该怎么办?要做到这一点,您需要多行代码:
render(){
const{myImage,myName,myJobType,myPrice}=this.props.location.myInfo | |{};
如果(!this.props.location.myInfo){
this.props.history.push(“/”)
}
返回(
//...
)
}
或
componentDidMount(){
如果(!this.props.location.myInfo){
this.props.history.push(“/”)
}
}
render(){
const{myImage,myName,myJobType,myPrice}=this.props.location.myInfo | |{};
返回
(
//...
)
}
谢谢你的回答,不过我后来用{this.props.location.hotelInfo!==未定义的&&…
将我的
的内部包装起来,并将其修复。我也将尝试这两个选项,然后返回相应的评分。谢谢