在 render() 之前使用什么组件生命周期来做某事? [英] What component lifecycle to use to do something before render()?
问题描述
我需要检查一些道具(来自 redux 商店)是否为空对象.如果它是空的,我希望页面重定向到另一个页面而不是调用 render()
.
I need to check whether some props (from redux store) is an empty object or not. If it is empty, I want the page to redirect to another page and not bother to call render()
.
目前的流程是这样的:
constructor(props) {
this.checkObject();
}
checkObject() {
if (Object.keys(someObj).length === 0 && someObj.constructor === Object) {
this.props.history.push("/some-other-route");
}
}
render() {
// some code
}
但是,当我执行 console.log
时,在 checkObject()
之后调用 render()
这会导致一些错误,因为 render()
需要一个非空对象才能正确显示内容.这就是为什么如果对象为空(我通过 checkObject()
检查),我什至不想调用 render()
并且只是重定向到另一个页面的原因.
However, when I do a console.log
, render()
is being called after checkObject()
which causes some errors because render()
needs a non-empty object to display content properly. That's the reason I don't want react to even call render()
if the object is empty (which I check through checkObject()
) and just redirect to another page.
那么是否有生命周期方法可以在调用 render()
之前执行我的重定向代码?
So is there a lifecycle method to use that will execute my redirection code before render()
is called?
推荐答案
你可以在 render 中使用 react-router 的 Redirect 组件.
You could use the Redirect component of react-router within render.
import { Redirect } from 'react-router'
render(){
(checkIfObjectEmpty)?<Redirect to = '/some_route'/>:<JSX>
}
这篇关于在 render() 之前使用什么组件生命周期来做某事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!