reactjs - 在另一个 axios 请求中使用 axios 响应数据

标签 reactjs axios state

我正在使用 axios 获取信息,并且我需要在不同 axios 响应的另一个处理程序中使用该信息。我似乎无法在第二个响应处理中使用第一个响应中加载的数据。

例如:

const [firstData, setFirstData] = useState({});
const [secondData, setSecondData] = useState({});

await axios.get("url/firstRoute").then((response) => {
    setFirstData(response.data);
}).then(async () => {
    await axios.get("url/secondRoute").then((response) => {
        setSecondData(firstData); // firstData is still an empty Object here for some reason
    })
});

当我处于第二个请求时,如何确保 firstData 不为空? 我还尝试对 firstData 使用 useEffect Hook ,并在其中调用第二个 axios 请求,但我仍然得到 firstData 为空的相同结果。 (假设两个请求都返回数据)

最佳答案

您可以像这样从第一个 .then 返回值:

await axios
  .get('url/firstRoute')
  .then((response) => {
    setFirstData(response.data);
    return response.data;
  })
  .then(async (firstData) => {
    await axios.get('url/secondRoute').then((response) => {
      setSecondData(firstData); // firstData is still an empty Object here for some reason
    });
  });

在您的代码中,您正在设置状态,但它没有在您的 then 子句之前完成。

关于reactjs - 在另一个 axios 请求中使用 axios 响应数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64042481/

相关文章:

arrays - React this.state 未定义数组

javascript - ReactJs 不更新状态

javascript - 为什么我的状态没有在此组件中设置

eclipse - 有没有适用于 React JS 的 eclipse 插件

reactjs - React Router BrowserRouter History Push & Google Analytics

javascript - React - Axios promise 未定义的未决值

vue.js - 如何修复 axios 中的 'TypeError: name.toUpperCase is not a function'

javascript - React 中 HTML 输入类型数值四舍五入到小数点后两位

javascript - 何时使用 componentWillMount 而不是 componentDidMount

node.js - 使用 axios 调用登录 API 时,当我的凭据在 catch 中错误时,我没有收到任何响应