【问题标题】:Is there a way to setState of an array in a .then() block?有没有办法在 .then() 块中设置数组的状态?
【发布时间】:2021-12-02 17:45:24
【问题描述】:

`

  1. 我有一个点数组(城市、州)
  2. 我进行 fetch 调用以将我的点转换为(经纬度),因此我将结果推送到数组并尝试设置数组的 setState,但是当我使用 console.log(array) 时,我得到了 []。 `
if (pointsComplete) {
        // for  (let i = 0; i < pointsComplete.length; i++) {
        for await (let x of pointsComplete) {
          if (x.city !== "") {
            fetch(
              `https://singlesearch.alk.com/na/api/search?&query=${x.city} , ${x.state}&maxResults=1`,
              {
                method: "GET",
                headers: {
                  "Content-Type": "application/json",
                  Authorization: trimble_key,
                },
              }
            )
              .then((response) => response.json())
              .then((data) => {
                pointsCoords.push({
                  Lat: data.Locations[0].Coords.Lat,
                  Long: data.Locations[0].Coords.Lon,
                  position: parseInt(x.position),
                });
              })
              .finally(() => {
                setPointsCoordsArray(pointsCoords);
              });
          }
        }
      }

【问题讨论】:

标签: javascript arrays reactjs setstate


【解决方案1】:

这对我有用..

if (pointsComplete) {
        let promises = [];
        for (let x of pointsComplete) {
          if (x.city !== "") {
            promises.push(
              fetch(
                `https://singlesearch.alk.com/na/api/search?&query=${x.city} , ${x.state}&maxResults=1`,
                {
                  method: "GET",
                  headers: {
                    "Content-Type": "application/json",
                    Authorization: trimble_key,
                  },
                }
              )
                .then((response) => response.json())
                .then((data) => {
                  pointsCoords.push({
                    Lat: data.Locations[0].Coords.Lat,
                    Long: data.Locations[0].Coords.Lon,
                    position: parseInt(x.position),
                  });
                })
            );
          }
        }

        Promise.all(promises).then((data) => {
          setPointsCoordsArray(pointsCoords);
          console.log("______________");
       
        });
      }

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2013-03-13
    • 2019-06-03
    • 2021-06-27
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多