我怎样才能简单地请求 axios.all 在 React 中使用带有字符串数组的循环?

How can I simply request axios.all using loop with array of strings in React?

请先检查我的代码。

const arr = ['liver', 'heart', 'brain']

const url1 = `www.hospital.com/diseaseName?liver`
const url2 = `www.hospital.com/diseaseName?heart`
const url3 = `www.hospital.com/diseaseName?brain`

const request1 = axios.get(url1)
const request2 = axios.get(url2)
const request3 = axios.get(url3)

const fetchData = () => {
  axios.all( [request1, request2, request3] )
  .then(axios.spread((...response) => {
  const responseOne = response[0].data
  const responseTwo = response[1].data
  const responseThree = response[2].data
  })
}

我想做的是使用 arr 的每个元素,使每个项目的 url,并使用 axios.all[=12 请求=]

我想我可以使用 array.map 等循环函数或其他方法来简化代码。我需要一些指导。谢谢。

你可以这样做。

const URL = 'www.hospital.com/diseaseName';
const arr = ['liver', 'heart', 'brain'];


const requests = arr.map((a) => {
return axios.get(URL + '?' + a);
});


const fetchData = () => {
  axios.all( requests )
  .then(axios.spread((...response) => {
  const responseOne = response[0].data
  const responseTwo = response[1].data
  const responseThree = response[2].data
  })
}