React 之条件渲染方式总结~欢迎补充~

129 阅读1分钟

React 条件渲染方式总结

  • 条件渲染之 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>
  );
}
  • 条件渲染之 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>
  );
}
  • 条件渲染之 三选表达式
function Recipe({ food, isEdit }) {
  return (
    <div>
      {food.name}
 
      {isEdit ? (
        <EditRecipe food={food} />
      ) : (
        <ShowRecipe food={food} />
      )}
    </div>
  );
}
  • 条件渲染之 &&
function LoadingIndicator({ isLoading }) {
  return <div>{isLoading && <p>Loading...</p>}</div>;
}
  • 条件渲染之 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>
  );
}
  • 多条件渲染 利用枚举(简单策略模式)
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> 
  );
}

不依赖[状态]的时候

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

利用函数

 
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>;
}
  • 高阶组件
 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>
  );
}
  • 借助第三方库
<Choose>
  <When condition={isLoading}>
    <div><p>Loading...</p></div>
  </When>
  <Otherwise>
    <div>{list.map(item => <Item item={item} />)}</div>
  </Otherwise>
</Choose>
  • 利用es6 map对象### 原理和第六点是一样的(感觉更高级一丢丢)