foreach中是否有条件声明?

时间:2019-01-10 03:41:51

标签: javascript reactjs

我有一个用于填充表格的API响应。我正在分配指向表项的链接,但是如果API方法(getPreauthorizedLink)的响应为空字符串,则不提供任何链接/将表项显示为空字符串。例如,如果element.executiveLink是一个空字符串,那么我不想为该表元素分配链接,而只是将其设置为空字符串。

这是我的代码:

  componentDidMount() {
    const _self = this;

    fetch(config.api.urlFor('xxx'))
    .then((response) => response.json())
    .then((data) => {

      const tableContent = [];

      data.array.forEach(element => {
        tableContent.push({
          provider: element.provider,
          type: element.type,
          executiveLink: <Link to='' onClick={(e)=> {e.preventDefault(); this.getPreauthorizedLink(element.executiveLink)}}>Report</Link>,
          detailedLink: <Link to='' onClick={(e)=> {e.preventDefault(); this.getPreauthorizedLink(element.detailedLink)}}>Report</Link>,
          providerLink: <Link to='' onClick={(e)=> {e.preventDefault(); this.getPreauthorizedLink(element.providerLink)}}>Report</Link>
        });

      })

      this.setState({reportJSON: tableContent || [], tableIsBusy: false})

    })
    .catch((err) => _self.setState({tableIsBusy: false }));
  }

1 个答案:

答案 0 :(得分:2)

尝试使用short if语句:

        tableContent.push({
          provider: element.provider,
          type: element.type,
          executiveLink: element.executiveLink ? <Link to='' onClick={(e)=> {e.preventDefault(); this.getPreauthorizedLink(element.executiveLink)}}>Report</Link> : "",
          detailedLink: <Link to='' onClick={(e)=> {e.preventDefault(); this.getPreauthorizedLink(element.detailedLink)}}>Report</Link>,
          providerLink: <Link to='' onClick={(e)=> {e.preventDefault(); this.getPreauthorizedLink(element.providerLink)}}>Report</Link>
        }