【问题标题】:Splitting an array of info to send request and receive info properly React JavaScript拆分信息数组以正确发送请求和接收信息 React JavaScript
【发布时间】:2020-08-22 17:45:41
【问题描述】:

我想使用一些 id 从 api 接收一些信息,然后保存信息以供以后使用:

function useJobs () {
 const [tags, setTags] = React.useState({})
  React.useEffect(() => {
    async function fetchTags () {
      const tPromises = []
      for (const job of jobs) {
        console.log(job.tags)
        tPromises.push(fetchJSON(`/api/jobs/view-tag/${job.tags}`, { headers: headers })
          .then((tags) => {
            return { [job.id]: tags }
          }))
      }
      const dData = await Promise.all(tPromises)
      console.log(dData)
      setTags(prev => Object.assign({}, ...dData))
    }
    fetchTags()
  }, [jobs])

  return [jobs, locations, departments, tags]
}

function useJobs () {
const [jobs, locations, departments, tags] = useJobs()
......
{tags[job.id] && <Col key={tags[job.id].id}>Tags:{tags[job.id].name} </Col>}

但由于job.tags 是一个数组而不是单个字符串,我无法正确发送我的请求,并且收到如下错误:

"GET /api/jobs/view-tag/10,12,13 HTTP/1.1" 404 7681

如何将job.tags 数组拆分为各个部分并为每个部分发送请求并接收它们的信息?

这是我的 job.tags 数组(我有 3 个作业对象,在数组内部,每个作业都需要发送标签 ID)

【问题讨论】:

  • job.tags 是数组的数组吗?
  • for (const job of jobs) { console.log(job.tags)} 照片是这个@Yousaf 的结果
  • 我有 3 个工作,每个工作都有一组标签,@Yousaf 中有这些 id

标签: javascript arrays reactjs react-hooks


【解决方案1】:

您需要遍历每个 job.tags 数组并在请求中发送单独的标签 ID

您也不需要循环内的then 块。 Promise.All 将在所有承诺都被推入tPromises 数组后解决承诺

for (const job of jobs) {
   for (const tagId of job.tag) {

       tPromises.push(fetchJSON(`/api/jobs/view-tag/${tagId}`, {headers: headers})

   }
}

const dData = await Promise.all(tPromises)
console.log(dData)

【讨论】:

    【解决方案2】:

    试试这个:

    for (const job of jobs) {
      for (const tag of job.tag) {
        console.log(tag)
        tPromises.push(fetchJSON(`/api/jobs/view-tag/${tag}`, { headers: headers })
          .then((tags) => {
            return { [job.id]: tags }
        }))
      }
    }
    

    【讨论】:

    • 这个有效,但它只为每个元素返回一个标签,例如数组中的标签是 css,js,html 但这只打印 css
    • 那是因为你在循环承诺。它需要等待jobs中每个job中每个标签的响应
    • 那么如果我想让它们都显示出来该怎么办呢?
    猜你喜欢
    • 1970-01-01
    • 2021-12-16
    • 2023-01-27
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    相关资源
    最近更新 更多