在 react-native 中调用 Api 时如何映射 returns 的数据

How to map data which returns when making Api call in react-native

我正在拨打 Api 电话,我会在那里获得地址列表。

const [address_line1, setAddress_line1] = React.useState([]);

我可以在控制台中得到结果。 下面是调用 api 后我的代码片段:

if (result.status === 200 && result.data.status === "success") {
  for (let index = 0; index < 3; index++) {
    console.log(result.data.data[index].city);
    setAddress_line1(result.data.data[index].city);
  }
}

控制台输出:

delhi
Mumbai
Pune

我正在尝试在代码中映射此输出:

<ScrollView showsVerticalScrollIndicator={false}>
  {address_line1.map((item, index) => (
    <TouchableOpacity
      index={index}
      onPress={() => setIndexSelect(index)}
      key={index}
    >
      <Text>{item}</Text>
    </TouchableOpacity>
  ))}
</ScrollView>;

但我收到错误消息:

address_line1.map is not a function

我知道我映射输出的地方有问题,但我无法弄清楚。我已经尝试了几个小时。我需要一些帮助!!

试试这个方法

if (result.status === 200 && result.data.status === "success") {
  const data = [];
  for (let index = 0; index < 3; index++) {
    console.log(result.data.data[index].city);
    data.push(result.data.data[index].city);
  }
  setAddress_line1(data);
}

您也可以使用 reduce 或 map

useEffect(() => {
      if (result.status === 200 && result.data.status === "success") {
      const addresses = result.data.data.map(elem=>elem.city)
      setAddress_line1(addresses);
    }
    });

这样你循环所有数据和return城市