在渲染我的组件之前,我需要获取一些信息。该信息将由API提供,并通过ajax调用获取。
我只是想在渲染组件之前等待10秒钟,但是它说:
Uncaught Invariant Violation: Login.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.
兑现承诺后,我可以渲染我的组件吗?
/** Page Login */ class Login extends React.Component { /** * @constructor * @param {object} props La fonction super() appelle le parent pour y transmettre ses propriétés */ constructor(props) { super(props); this.handleFormSubmit = this.handleFormSubmit.bind(this); } /** * Reçoit les valeurs des formulaires */ handleFormSubmit(data) { const { dispatch } = this.props; dispatch(fetchLoginAuth(data)); } normalRender() { return ( <div id="login-page"> <div className="container-fluid"> <div className="row"> <div className="col-md-2"> <Link to="/" className="home-link"><img src={BASE_URL + '/assets/img/logo.svg'} alt="Logo" /></Link> </div> </div> <div className="row"> <div className="col-lg-4 col-lg-offset-4"> <h1><FormattedMessage {...messages.loginPageTitle} /></h1> </div> </div> {React.cloneElement(this.props.children || <div />, { onSubmit: this.handleFormSubmit, login: this.props.login })} </div> </div> ); } /** * Render le component - ReactTransitionGroup * @return {JSX} Rend la page Registration */ render() { setTimeout(this.normalRender, 10000); } }
我将ES6与JSX,redux(带有react-router的通用路由器)一起使用。
非常感谢您的帮助!
这是我通常做的事情:
class Login extends React.Component { constructor(props) { //IMPLEMENT OTHER JUNK HERE this.state = { data: null //This is what our data will eventually be loaded into }; } componentDidMount() { this.loadData(); } loadData() { /*LOAD DATA, INSERT BELOW LINE IN CALLBACK FUNCTION this.setState({ data: //LOADED DATA }); */ } render() { if (!this.state.data) { return <div /> } //WE HAVE DATA, DO A NORMAL RENDER return ( <div id="login-page"> <div className="container-fluid"> <div className="row"> <div className="col-md-2"> <Link to="/" className="home-link"><img src={BASE_URL + '/assets/img/logo.svg'} alt="Logo" /></Link> </div> </div> <div className="row"> <div className="col-lg-4 col-lg-offset-4"> <h1><FormattedMessage {...messages.loginPageTitle} /></h1> </div> </div> {React.cloneElement(this.props.children || <div />, { onSubmit: this.handleFormSubmit, login: this.props.login })} </div> </div> ); } }
这是将要发生的事情的细分…
this.state.data
null
<div />
this.setState()
编辑(2019年10月11日):将componentWillMount()迁移到componentDidMount()