React之条件渲染(学习和总结)

在实际开发中经常会遇到条件渲染,一般都是通过if else 语句、三元运算符、switch case 语句来实现,这里记录并学习一下

1:条件渲染之 IF

const users = [
  { id: '1', firstName: 'Robin', lastName: 'Wieruch' },
  { id: '2', firstName: 'Dennis', lastName: 'Wieruch' },
];
 
function App() {
  return (
    <div>
      <h1>Hello Conditional Rendering</h1>
      <List list={users} />
    </div>
  );
}
 
function List({ list }) {
  // 保护模式
  if (!list) {
    return null;
  }
 
  return (
    <ul>
      {list.map(item => (
        <Item key={item.id} item={item} />
      ))}
    </ul>
  );
}
 
function Item({ item }) {
  return (
    <li>
      {item.firstName} {item.lastName}
    </li>
  );
}

2:条件渲染之IF ELSE 

function List({ list }) {
  if (!list) {
    return null;
  }
 
  if (!list.length) {
    return <p>Sorry, the list is empty.</p>;
  } else {
    return (
      <div>
        {list.map(item => (
          <Item item={item} />
        ))}
      </div>
    );
  }
}
function List({ list }) {
  if (!list) {
    return null;
  }
 
  if (!list.length) {
    return <p>Sorry, the list is empty.</p>;
  }
 
  return (
    <div>
      {list.map(item => (
        <Item item={item} />
      ))}
    </div>
  );
}

3:条件渲染之三元表达式

function Recipe({ food, isEdit }) {
  return (
    <div>
      {food.name}
 
      {isEdit ? (
        <EditRecipe food={food} />
      ) : (
        <ShowRecipe food={food} />
      )}
    </div>
  );
}

4:条件渲染之 && 

function LoadingIndicator({ isLoading }) {
  return <div>{isLoading && <p>Loading...</p>}</div>;
}

5:条件渲染之 SWITCH CASE

function Notification({ text, status }) {
  switch (status) {
    case 'info':
      return <Info text={text} />;
    case 'warning':
      return <Warning text={text} />;
    case 'error':
      return <Error text={text} />;
    default:
      return null;
  }
}
function Notification({ text, status }) {
  return (
    <div>
      {(function() {
        switch (status) {
          case 'info':
            return <Info text={text} />;
          case 'warning':
            return <Warning text={text} />;
          case 'error':
            return <Error text={text} />;
          default:
            return null;
        }
      })()}
    </div>
  );
}
function Notification({ text, status }) {
  return (
    <div>
      {(() => {
        switch (status) {
          case 'info':
            return <Info text={text} />;
          case 'warning':
            return <Warning text={text} />;
          case 'error':
            return <Error text={text} />;
          default:
            return null;
        }
      })()}
    </div>
  );
}

6:多个条件渲染

(1)利用枚举

const NOTIFICATION_STATES = {
  info: 'Did you know? ...',
  warning: 'Be careful here ...',
  error: 'Something went wrong ...',
};

function Notification({ text, status }) {
  return (
    <div>
      {
        {
          info: <Info text={text} />,
          warning: <Warning text={text} />,
          error: <Error text={text} />,
        }[status]
      }
    </div>
  );
}

(2) 不依赖[状态]的时候


const NOTIFICATION_STATES = {
  info: <Info />,
  warning: <Warning />,
  error: <Error />,
};
 
function Notification({ status }) {
  return (
    <div>
      {NOTIFICATION_STATES[status]}
    </div>
  );
}

(3)利用函数


const getNotification = text => ({
  info: <Info text={text} />,
  warning: <Warning text={text} />,
  error: <Error text={text} />,
});
 
function Notification({ status, text }) {
  return <div>{getNotification(text)[status]}</div>;
}

7:高阶组件

function withLoadingIndicator(Component) {
  return function EnhancedComponent({ isLoading, ...props }) {
    if (!isLoading) {
      return <Component {...props} />;
    }
 
    return (
      <div>
        <p>Loading</p>
      </div>
    );
  };
}
 
const ListWithLoadingIndicator = withLoadingIndicator(List);
 
function App({ list, isLoading }) {
  return (
    <div>
      <h1>Hello Conditional Rendering</h1>
 
      <ListWithLoadingIndicator isLoading={isLoading} list={list} />
    </div>
  );
}

8:借助其他库

<Choose>
  <When condition={isLoading}>
    <div><p>Loading...</p></div>
  </When>
  <Otherwise>
    <div>{list.map(item => <Item item={item} />)}</div>
  </Otherwise>
</Choose>

9:利用es6 Map对象  原理和第六点是一样的(高级一丢丢)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

superTiger_y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值