如何使用JavaScript遍历表?

时间:2019-03-06 21:47:37

标签: javascript reactjs lodash

我有一个需要动态添加数据的表,所需的列数将取决于有多少服务提供者。我想遍历表的tr和td,但是现在我只是想在表中添加一个forEach语句,但是出现以下错误:未捕获的不变违规:对象作为React子对象无效(找到:object按键

enter image description here

有人知道如何使用React或Lodash做到这一点吗?

          <table className='table-body'>
            <tbody>
              {
                forEach(leadServiceProviderComparison.response.assignedServiceProviders, (provider) => {
                  console.log('provider: ', provider);
                })
              }
              <tr style={{height: '65px'}}>
                  <th>Gatlin Plumbing &#38; Heatings</th>
                  <th>St. John Plumbing, Inc.</th>
                  <th>Budget Right Handyman</th>
                  <th>Plumbing Company</th>
              </tr>

enter image description here

2 个答案:

答案 0 :(得分:0)

您不能像这样使用forEach。 如果要遍历从数据API中获得的一系列信息,请尝试使用map

Map在所有阵列上均受支持,因此您不需要Lodash。

有关示例,请参见https://reactjs.org/docs/lists-and-keys.html

答案 1 :(得分:-1)

tbody内部:

    {
              leadServiceProviderComparison.response.assignedServiceProviders.map((provider,index)=>return(
                 <tr key={index} style={{height: '65px'}}>
                      <th>Gatlin Plumbing &#38; Heatings</th>
                      <th>St. John Plumbing, Inc.</th>
                      <th>Budget Right Handyman</th>
                      <th>Plumbing Company</th>
                  </tr>
);)
    }