Reactjs 循环和更新变量而不是覆盖变量时,使用React Native

Reactjs 循环和更新变量而不是覆盖变量时,使用React Native,reactjs,react-native,expo,Reactjs,React Native,Expo,我是一个母语为React的初学者。我的程序中有一个循环,它遍历API的一些结果,对于每个结果(邮政编码),它会在地图上放置一个带有相应坐标的pin const showPostcode = async() => { {parkingPostcode && parkingPostcode.map((val, index) => { console.log(val.postcode); searchMultipleSpaces(val.postco

我是一个母语为React的初学者。我的程序中有一个循环,它遍历API的一些结果,对于每个结果(邮政编码),它会在地图上放置一个带有相应坐标的pin

const showPostcode = async() => {

  {parkingPostcode && parkingPostcode.map((val, index) => {

    console.log(val.postcode);
    searchMultipleSpaces(val.postcode)
    console.log("=============")

    key={index}

  })}

}
上面的函数是遍历从API收集的结果的循环

如您所见,它调用另一个函数
searchMultipleSpaces(val.postcode)
。 以下是函数:

const searchMultipleSpaces = async(postcodee) => {
  const response = await camdenParking.get("", {

    params:{
      postcode: postcodee
    }

  })

  setparkingSpaces(response.data)   
}
如您所见,在第二个函数中,我们使用API返回的任何内容设置
setparkingspace
。问题是,对于每个不同的迭代,数据都将被覆盖。因此,最终数据将只包含上一次迭代的结果。我应该怎么做才能使所有迭代的每个结果都保存在那里而不被覆盖

这是我使用停车空间的地方:

                {parkingSpaces.map((val, index) => {
                return (<MapView.Marker
                        coordinate={{
                        latitude: parseFloat(val.latitude),
                        longitude:parseFloat(val.longitude)
                        }}
                        key={index}
{parkingspace.map((val,index)=>{

return(建议您将searchMultipleSpaces函数转换为promise,并立即调用所有函数,如下所示

const showPostcode = async() => {
   let allPromise = [];
  {parkingPostcode && parkingPostcode.map((val, index) => {

     console.log(val.postcode);
     allPromise.push(searchMultipleSpaces(val.postcode))
     console.log("=============")

     key={index}

   })}

   const data = await Promise.all(allPromise);

  //here you get all the response at once and then send it to setparkingSpaces

   setparkingSpaces(data)   

}
我改变的是,我没有返回整个响应,而是在其中做出新的承诺,然后解析响应的数据元素

然后用

如下

const showPostcode = async() => {
   let allPromise = [];
  {parkingPostcode && parkingPostcode.map((val, index) => {

     console.log(val.postcode);
     allPromise.push(searchMultipleSpaces(val.postcode))
     console.log("=============")

     key={index}

   })}

   const data = await Promise.all(allPromise);

  //here you get all the response at once and then send it to setparkingSpaces

   setparkingSpaces(data)   

}

您应该将新数据附加到状态,而不是覆盖它,如下所示:


setparkingSpaces(prevSpaces=>[…prevSpaces,…response.data])

您在setparkingSpaces functionconst[parkingSpaces,setparkingSpaces]=useState([])中执行的操作,它只是一个状态,所以您要做的是存储“response.data”数组然而,在SetParkingSpace中,我一次搜索多个邮政编码,结果SetParkingSpace()中的值被覆盖因为它只会保留最后一个邮政编码的response.data,因为其余的都被覆盖了Hanks,但是,这会引发另一个错误。当我尝试使用数据时,它会显示不变冲突。我会更新我的帖子,以便您可以看到我想在哪里使用ParkingSpaces。当我搜索API时,我需要数据对象,而不是整个数组。这就是为什么我有response2.data。我怎么能只从api回复中选择数据呢?好吧,基本上你不需要整个响应,你只需要响应中的数据对象。我得到了同样的错误。我真的不知道下一步该怎么做。我如何共享它?