无法在React JS中循环

时间:2019-02-19 12:03:36

标签: javascript arrays reactjs jsx

我正在尝试使用.map进行简单的循环,但未获得预期的输出。这是我的代码-

const filters = [this.state.filterAttributes ] //[Part Number, Product Line]

<tr key = {key}>

    {filters.map((k) => {

        return <th>{k}</th>
    })}

    <td>{item.PartNumber}</td>
    <td>{item.productline}</td>
</tr>

th{k}返回的是<th>Part NumberProduct Line</th>而不是

<th>Part Number</th>
<th>Product Line</th>

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

发生这种情况是由于以下行:

const filters = [this.state.filterAttributes] //[Part Number, Product Line]

现在,filters将具有以下值:

[[this.state.filterAttributes]]

const a = ['Part Number', 'Product Line']
const filters = [a]

console.log(filters)

您尝试使用解构运算符执行以下操作来复制数组:

const filters = [...this.state.filterAttributes]

const a = ['Part Number', 'Product Line']
const filters = [...a]

console.log(filters)

此外,这是map渲染的较短语法:

{filters.map(k => <th key={k}>{k}</th>)} //Do not forget the key

您还可以从状态中提取值,而不是通过使用解构来复制它:

const { filterAttributes } = this.state

<tr key={key}>

    {filterAttribute.map(k => <th key={k}>{k}</th>)}

    <td>{item.PartNumber}</td>
    <td>{item.productline}</td>
</tr>