在React中有条件地渲染

时间:2018-05-12 21:04:55

标签: reactjs

我想根据用户是否登录来渲染两个完全独立的组件。 这是我的代码,

import React, {Component} from 'react';
import ContainerLogged from './components/logged/ContainerLogged'
import ContainerUnlogged from './components/unlogged/ContainerUnlogged'

class App extends Component {
    constructor(props){
        super(props)
        this.state = {isLoggedIn : false}
    }
    render(){
        const comp = this.state.isLoggedIn ? (
            <ContainerLogged />
        ): (
            <ContainerUnlogged />
        );
        return (

            {comp}
        );
    }
}
export default App;

这是我的index.js

import 'normalize.css';
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

我收到以下错误,

Objects are not valid as a React child (found: object with keys {comp}). If you meant to render a collection of children, use an array instead.
    in App (at index.js:8)

我是React的新手,因此不明白这里发生了什么。

3 个答案:

答案 0 :(得分:2)

而不是

return (

    {comp}
);

尝试

return comp;

答案 1 :(得分:1)

{comp}是一个具有键comp的对象,并且值为变量comp的值。这在这里确实很有道理。 (那是ES2015&#34;速记属性名称&#34;功能)

您必须简单地返回comp而不是对象:return comp

答案 2 :(得分:1)

你是正确的方向,我建议打破你的渲染功能,当你有条件逻辑时它总是有帮助。

import React, { Component } from 'react';
import { render } from 'react-dom';

class App extends Component {
  constructor() {
    super();
    this.state = {
      isLoggedIn: false
    };
  }

  renderLoggedIn = () => {
    return (
      <div>
        <h2>Logged In</h2>
      </div>
    );
  }
  renderNotLoggedIn = () => {
    return (
      <div>
        <h2>Not Logged In</h2>
      </div>
    );
  }
  render() {
    let element = null;
    if (this.state.isLoggedIn) {
      element = this.renderLoggedIn();
    } else {
      element = this.renderNotLoggedIn();
    }
    return element;
  }
}

render(<App />, document.getElementById('root'));