如何在API响应的useState中存储多个值?

问题描述 投票:0回答:2

我正在用另一个 API 调用一个 API。

第一个 API 有像标签一样的列表:

{
    "body": [
        {
            "label": "label one",
            "inputVal": "input value one"
        },
        {
            "label": "label two",
            "inputVal": "input value two"
        }
    ]
}

第二个 API 将验证我们在第一个 API 中使用的每个标签和输入:

所以我至少调用第二个 API 两次,因为我需要像第一个 API 一样验证两个标签和输入。

const [inputVal, setInputVal] = useState([]);

async function firstApi() {
    axios
      .post('first_api_url', {
        title: "title",
      })
      .then((res) => {
        if (res) {
          res.data.body.forEach((val) => {
            secondApi();
          });
        }
      });
  }

async function secondApi() {
    axios
      .post('second_api_url', {
        titleSecondApi: "titleSecondApi",
      })
      .then((res) => {
       if (res.data.body.msg) {
          setInputVal([res.data.body.msg]);
          console.log(inputVal);
        }
      });
}

现在我只收到第二个 API 响应最后一个响应,但我需要数组中的所有响应。

我正在使用 inputVal useState ,但没有获取数组中的所有值。如何获得?

javascript reactjs
2个回答
1
投票

如果我正确理解了你的观点,你可以尝试这样更改你的代码:

const [inputVal, setInputVal] = useState([]);

async function firstApi() {
    axios
      .post('first_api_url', {
        title: "title",
      })
      .then((res) => {
        if (res) {
          res.data.body.forEach((val) => {
            secondApi();
          });
        }
      });
  }

async function secondApi() {
    axios
      .post('second_api_url', {
        titleSecondApi: "titleSecondApi",
      })
      .then((res) => {
       if (res.data.body.msg) {
          setInputVal(prev=> {
            return [...prev, res.data.body.msg]
          });
          console.log(inputVal);
        }
      });
}

1
投票

目前,您正在使用新数组覆盖您的状态。您需要保留之前的回复。为此,您需要在第二个 API 的 then 块中更新 setter,如下所示:

setInputVal(previous => [...previous, res.data.body.msg]);

您可以在此处了解有关 在 javascript 数组中传播的更多信息

© www.soinside.com 2019 - 2024. All rights reserved.