【问题标题】:Condition render functional component with multiple case and complex logic条件渲染功能组件具有多案例和复杂的逻辑
【发布时间】:2019-12-20 04:19:30
【问题描述】:

我是 React 的功能组件和新 Hook 功能的新手。目前我有一个条件渲染的用例,它具有复杂的逻辑和多案例(不能简单地使用开关案例、三元或枚举渲染)。看下面的示例代码:

const conditionRender = condition => {
  if (condition < 0) {
    return <Component1 />
  }
  if (condition < 12) {
    return <Component2 />
  }
  if (condition < 50) {
    return <Component3 />
  }
  if (condition < 100) {
    return <Component4 />
  }
  if (condition % 2 === 0) {
    return <Component5 />
  }
}

function App() {
  return (
    <div className="App">
    {conditionRender(condition)}
    </div>
  );
}

我为此使用了函数组件之外的函数。这是最佳做法吗?或者您可以为此提出最佳建议。谢谢

【问题讨论】:

  • 对此没有特定的最佳实践。你做的没问题。
  • 这看起来像是用于您的案例的完全有效的模式。您也可以使用 switch 语句,但功能相同 - 仅取决于个人喜好。
  • 另请参阅此处以获取有关条件渲染的更多信息(但您的示例很好):reactjs.org/docs/conditional-rendering.html
  • 谢谢你的好回复,只是假设有任何其他更好的方法

标签: reactjs conditional-statements react-hooks


【解决方案1】:

最后只返回一个空值,因为如果没有一个条件匹配,那么它不会返回任何东西

const conditionRender = condition => {
  if (condition < 0) {
    return <Component1 />
  }
  if (condition < 12) {
    return <Component2 />
  }
  if (condition < 50) {
    return <Component3 />
  }
  if (condition < 100) {
    return <Component4 />
  }
  if (condition % 2 === 0) {
    return <Component5 />
  }
return null
}

【讨论】:

  • 是的,我在示例代码中遗漏了它,但这不是我提到的问题,顺便说一句,谢谢您的建议
  • @QuocVanTang 我在您发布的描述中没有看到任何问题。只是我看到最后的回报不见了,所以这就是我发布这个的原因。除了一切都很好
猜你喜欢
  • 1970-01-01
  • 2019-03-09
  • 2021-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-04
  • 2020-03-26
  • 1970-01-01
相关资源
最近更新 更多