简体   繁体   English

如何避免渲染中的嵌套三元?

[英]How to avoid nested ternary in render?

This is my case:这是我的情况:

<Form onSubmit={submit}>
                    {something === 0 ?
                        (someData.length && someData.length > 0) ?
                            doSomething() : null :
                        (someOtherData.length && someOtherData.length > 0) ?
                            doSomethingElse() : null
                    }
</Form>

However, eslint rule is giving me error: Do not nest ternary expressions .但是, eslint 规则给了我错误: Do not nest ternary expressions

How can this be avoided?如何避免这种情况? Can if - else be written in return (...) which renders data? if - else 可以写成return (...)来呈现数据吗?

could you do the validations before the return of the render method你能在返回渲染方法之前做验证吗

render () {
  myComponent = <></>;

  if (something === 0) {
      if (someData.length && someData.length > 0) {
        myComponent = doSomething();
      }
  } else if (someOtherData.length && someOtherData.length > 0) {
      myComponent = doSomethingElse();
  }

  return (
    <Form onSubmit={submit}>
      {<myComponent/>}
    </Form>
  )
}

If you want the validations within the component you could try it this way如果您想要组件中的验证,您可以尝试这种方式

<Form onSubmit={submit}>
    {
      something === 0 && someData.length && someData.length > 0
        ? doSomething()
        : something !== 0 && someOtherData.length && someOtherData.length > 0 && doSomethingElse()
    }
</Form>

Encapsulate the behaviour into a function on the component将行为封装到组件上的 function

renderComponent() {
  return something ?
    someOtherData.length && doSomethingElse() :
    someData.length && doSomething();
}

render() {
  ...
  return (
    <Form onSubmit={submit}>
      {renderComponent()}
    </Form>
  );
}

Tip - you don't need to explicitly pass null , React supports conditional rendering提示 - 你不需要显式传递null ,React 支持条件渲染

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

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