React方法不返回表数据以显示

时间:2019-09-03 20:31:30

标签: reactjs

在React中,如果满足条件,我有一个三元运算符返回一个组件:

              { this.state.houseHoldGroup.length > 0 ? (
              <Table className="align-items-center table-flush" responsive>
                <thead className="thead-light">
                  <tr>
                    <th scope="col">First</th>
                    <th scope="col">Last</th>
                    <th scope="col"></th>
                    <th scope="col"></th>
                  </tr>
                </thead>
                <tbody>
                {this.checkHouseholdGroup()}
                </tbody>
              </Table>
            ) : null }

效果不错。 在此组件内,我有一个方法:this.checkHouseholdGroup()

此方法的预期行为是返回<tbody></tbody>内的表数据

checkHouseholdGroup = () => {
  const householdDetails = this.state.houseHoldGroup;
  householdDetails.forEach(el => {
    console.log(el.firstHousehold)
    return (
      <tr>
        <th scope="row">{el.firstHousehold}</th>
        <td>{el.lastHousehold}</td>
        <td>
        <Button
          color="primary"
          href="#pablo"
          onClick={e => e.preventDefault()}
          size="sm"
          onClick={e => this.submitMember(e)}>
          Update
        </Button>
        </td>
        <td>
        <Button
          color="primary"
          href="#pablo"
          onClick={e => e.preventDefault()}
          size="sm"
          onClick={e => this.submitMember(e)}>
          Delete
        </Button>
        </td>
      </tr>
    )
  })
}

我可以确认该元素具有数据。我console.log(el.firstHousehold)可以看到它不为空。我究竟做错了什么?预期的结果是它将返回我的数据。

2 个答案:

答案 0 :(得分:1)

您是否尝试过映射而不是使用forEach?

checkHouseholdGroup = () => {
  const householdDetails = this.state.houseHoldGroup;
  return householdDetails.map(el => {
    console.log(el.firstHousehold)
    return (
      <tr>
        <th scope="row">{el.firstHousehold}</th>
        <td>{el.lastHousehold}</td>
        <td>
        <Button
          color="primary"
          href="#pablo"
          onClick={e => e.preventDefault()}
          size="sm"
          onClick={e => this.submitMember(e)}>
          Update
        </Button>
        </td>
        <td>
        <Button
          color="primary"
          href="#pablo"
          onClick={e => e.preventDefault()}
          size="sm"
          onClick={e => this.submitMember(e)}>
          Delete
        </Button>
        </td>
      </tr>
    )
  })
}

答案 1 :(得分:0)

householdDetails.forEach替换为return householdDetails.map,您应该会很好。

forEach用于产生副作用-它不会返回任何内容。 checkHouseholdGroup的父组件等待返回值,但是该函数没有任何结果。 在return调用中使用forEach会使返回的值“无处”。这就是为什么需要使用map(ir返回包含元素的列表),然后返回数组的原因。