React_conditional rendering

In React, you can create different components to encapsulate the various behaviors you need. Then, depending on the state of the application, you can render only parts of the content in that state.

In Vue, we usually use the V-if instruction to do the conditional judgment.

Declare a variable

In the render function, we usually render content by variable judgment

  render() {
    const isLoggedIn = this.state.isLoggedIn;
    let button;
    if (isLoggedIn) {
      button = <A  />;
    } else {
      button = <B />;
    }
    return (
      <div>
        {button}
      </div>); }}Copy the code

Ternary operator

You can also use an operator in a return

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      {isLoggedIn
        ? <A />
        : <B />
      }
    </div>
  );
}
Copy the code

The and operator &&

Unreadmessages. length > 0 is executed only if unreadmessages. length > 0 is set

render() {
 return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }
    </div>
  );
  }
Copy the code