简体   繁体   English

短路评估 - React

[英]short circuit evaluation - React

Using a short circuit evaluation in a functional component (with hooks):在功能组件中使用短路评估(带钩子):

const Filters = () => {
  const [options, setOptions] = useState([]);

  return (
    <div className="row">
      {options.length > 0 && (
        <div className="col-md-3">
          <CustomComponent />
        </div>
      )}
    </div>
  )
}

Is there a way to render multiple elements right after an inline if condition?有没有办法在内联 if 条件之后立即呈现多个元素?

{options.length > 0 && (
  <div className="col-md-3">
    <CustomComponent />
  </div>
  <div className="col-md-3">
    <SecondComponent />
  </div>
)}

Code above doesn't work, react throws an error.上面的代码不起作用,反应会引发错误。 options array is filled after a promise resolved from useEffect() . options数组在useEffect()解析后填充。 That's why i've added this check, to display elements only when a promise resolved.这就是我添加此检查的原因,以便仅在承诺解决时显示元素。

UPDATED CODE for @wentjun: @wentjun 的更新代码:

return (
  {options.length > 0 && (
    <div className="row">
      <div className="col-md-3">
        <CustomComponent />
      </div>
    </div>
  )}
  )

This throws a syntax error.这会引发语法错误。

I think the error is due to returning two react elements.我认为错误是由于返回了两个反应元素。 Try wrapping then in fragment尝试包装然后在片段中

{options.length > 0 && (
  <>
    <div className="col-md-3">
      <CustomComponent />
    </div>
    <div className="col-md-3">
      <SecondComponent />
    </div>
  </>
)}

You should wrap the elements in React Fragments .您应该将元素包装在React Fragments 中 The reason being, React elements are rendered via a single root node element.原因是,React 元素是通过单个根节点元素呈现的。 Wrapping it in Fragments will allow you to group the elements without adding additional nodes.将它包装在 Fragments 中将允许您在不添加额外节点的情况下对元素进行分组。

return (
  <div className="row">
    {options.length > 0 && (
      <>
      <div className="col-md-3">
        <CustomComponent />
      </div>
      <div className="col-md-3">
        <SecondComponent />
      </div>
    </>
  )}
  </div>
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM