在render()之前使用什么组件生命周期来执行某些操作? [英] What component lifecycle to use to do something before render()?

查看:372
本文介绍了在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆