reactJS映射功能无法按预期工作

时间:2018-08-26 22:35:00

标签: javascript reactjs

我有一个reactJS应用程序,我试图在其中动态呈现一些我使用fetch()承诺读入的数据。这是我的应用程序的代码:

POST /login HTTP/1.1
Host: localhost:8080
Content-Type: application/json

{"username": "test","password": "test"}

这是我收到的错误消息:

username=test&password=test

这是我在render()函数中添加的console.log()的结果:

enter image description here

我不确定该错误告诉我什么或如何调试问题。

任何帮助将不胜感激。 谢谢。

4 个答案:

答案 0 :(得分:1)

array.push的返回类型是数组的新长度,也就是数字

因此您将状态属性productArray设置为一个数字,然后尝试调用未定义的number.map

如何解决?

先按一下,然后使用该数组设置状态

const updatedArray = [...currentComponent.state.productArray] 
updatedArray.push({ name: tempData.name, barcode: tempData.barcode })

currentComponent.setState({
   numberOfRecords: recordCount,
   productArray: updatedArray
}

资源: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

答案 1 :(得分:0)

根据MDN

  

push()方法将一个或多个元素添加到数组的末尾,并返回数组的新长度

您的代码似乎期望Array.push()将返回修改后的数组本身:

productArray: currentComponent.state.productArray.push(...

为防止状态损坏,应在调用setState()之前单独构造新数组。

答案 2 :(得分:0)

Array's push()函数returns integer,因此无法在其上调用map()函数。尝试将功能更改为:

currentComponent.setState({
  numberOfRecords: recordCount,
  productArray: [...currentComponent.state.productArray, { 
    name: tempData.name, 
    barcode: tempData.barcode 
  }]
})

答案 3 :(得分:0)

JavaScript Array.push方法不返回修改后的数组,而是返回该数组的新 length ,即数字。 JavaScript中的数字没有map方法。

您需要首先创建productArray的副本,然后推送新数据,最后设置状态:

const newProductArray = [...currentComponent.state.productArray]
newProductArray.push({ 
    name: tempData.name, 
    barcode: tempData.barcode 
})
currentComponent.setState(
    {
        numberOfRecords: recordCount,
        productArray: newProductArray
    }
)

请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

相关问题