如果数据库中没有与锁的id匹配的lockId
,我将尝试重定向到我的主路由。我正在从我的Redux州获得locks
。
此:
const lockId = this.props.match.params.lockId
const locks = this.props.locks || []
const lock = locks.find(lock => lock._id === lockId)
if(!lock) {
this.props.history.push('/')
}
工作正常,因为我可以看到我的url正在更改,但react仍然对我尖叫,说它找不到address
:
return (
<div>
<MainNavbar />
<Grid>
<Row className="show-grid">
<Col md={12}>
<h1 className="text-center">{lock.address.street}</h1>
我理解为什么,因为没有具有该id的锁,但这就是为什么我想将用户重定向到主屏幕。我应该使用其他类型的React生命周期方法吗,比如componentWillReceiveProps
?我很困,呵呵
编辑:
在评论中乔治的回答之后。你的意思是这样的吗?
componentDidMount() {
if (!this.props.lock) {
console.log("redirecting..")
this.props.history.push('/')
}
}
const lockId = this.props.match.params.itemId
const locks = this.props.locks || []
const lock = locks.find(lock => lock._id === lockId)
if(!lock) {
return null
}
我认为应该使用componentDidMount
,它发生在渲染之前。在render方法中,如果锁不存在,则应返回null。
我发现这是有效的:
if(!lock) {
window.location.href = '/'
}
但感觉这并不是React开发的最佳实践。