我如何将一个参数传递给API请求2,而API请求2是在react中从API响应1接收的。

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

我的2个API调用恰好在同一时间,API1的响应要作为请求参数发送给API2。但是,因为直到那个时候才被获取,所以值会变成undefined。有什么办法可以在react中解决这个问题。

reactjs react-native react-redux axios mobx
1个回答
1
投票

有多种方法来解决这个问题,我将解释一个最新的以及最寻求解决这个问题的方法。

我相信你一定听说过JavaScript中的asyncawait,如果你没有听说过,我建议你去看看围绕这个主题的MDN文档。

这里有2个关键词。异步 &&amp。等待,让我们逐一看看它们。

异步

在任何函数之前添加async意味着一件简单的事情,现在函数将返回一个简单的值,而不是正常的值。承诺

例如:

async function fetchData() {
 return ('some data from fetch call')
}

如果你在你的控制台中运行上述功能,只需通过 fetchData(). 你会发现,这个函数不是返回字符串值,而是有趣地返回一个 承诺.

所以简而言之async确保了函数返回一个承诺,并将非承诺包裹在其中。

Await

相信现在你已经猜到了,为什么我们除了使用关键词waiting之外,还使用了 异步,只是因为关键词 等待 使JavaScript等待,直到那个承诺(由async函数返回)确定下来并返回其结果。

现在来谈谈如何使用这个来解决你的问题,请按照下面的代码片断进行操作。

async function getUserData(){
 //make first request
 let response = await fetch('/api/user.json');
 let user     = await response.json();

 //using data from first request make second request/call
 let gitResponse = await fetch(`https://api.github.com/users/${user.name}`)
 let githubUser = await gitResponse.json()

 // show the avatar
  let img = document.createElement('img');
  img.src = githubUser.avatar_url;
  img.className = "promise-avatar-example";
  document.body.append(img);

 // wait 3 seconds
  await new Promise((resolve, reject) => setTimeout(resolve, 3000));

  img.remove();

  return githubUser;
}

正如你所看到的,上面的代码很容易阅读和理解。也可以参考 这个 文档,了解更多关于JavaScript中asyncawait关键字的信息。


0
投票

Asynawait解决了你的问题。

const requests = async () =>{
  const response1 = await fetch("api1")
  const result1 = await response1.json()

// Now you have result from api1 you might use it for body of api2 for exmaple
  const response2 = await fetch("api2", {method: "POST", body: result1})
  const result2 = await response1.json()
}

0
投票

如果你正在使用 反应钩,您可以使用 承诺 以链式方式调用你的API useEffect

useEffect(() => {
  fetchAPI1().then(fetchAPI2)
}, [])

相关的丹-阿布拉莫夫


-1
投票
fetch(api1_url).then(response => {
 fetch(api2_url, {
        method: "POST",
        body: response
  })
  .then(response2 => {
    console.log(response2)
   })
 })
})
.catch(function (error) {
   console.log(error)
 });

或者如果使用 axios

axios.post(api1_url, {
    paramName: 'paramValue'
})
  .then(response1 => {
     axios.post(api12_url, {
            paramName: response1.value
       })
  .then(response2 => {
     console.log(response2)
    })
  })
  .catch(function (error) {
     console.log(error);
  });
© www.soinside.com 2019 - 2024. All rights reserved.