【问题标题】:Unable to loop in react js无法在反应js中循环
【发布时间】:2019-02-19 12:03:35
【问题描述】:

我正在尝试使用 .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} 返回为 &lt;th&gt;Part NumberProduct Line&lt;/th&gt; 而不是

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

有人可以帮忙吗?

【问题讨论】:

    标签: javascript arrays reactjs jsx


    【解决方案1】:

    发生这种情况是因为以下行:

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多