繁体   English   中英

数组不显示其中的所有项目 React JavaScript

[英]Array doesnt display all of the items inside it React JavaScript

我根据一些 id 从 API 收到一些信息。 有 3 个作业对象,每个作业都有一个标签数组,在每个数组中,有一些 id 被发送到 API 以返回标签信息:

function useJobs () {
  const [jobs, setJobs] = React.useState([])
  const [locations, setLocations] = React.useState({})
  const [departments, setDepartments] = React.useState({})
  const [tags, setTags] = React.useState({})

  React.useEffect(() => {
    async function fetchTags () {
      const tPromises = []
      for (const job of jobs) {
        for (const tag of job.tags) {
          console.log(tag)
          tPromises.push(fetchJSON(`/api/jobs/view-tag/${tag}`, { 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]
}
export default function Jobs () {
 const [jobs, locations, departments, tags] = useJobs()
.....
{jobs.map(job => (
   {tags[job.id] && <Col key={tags[job.id].id}>Tags:{tags[job.id].name} </Col>}
)}
....
}

问题是每个作业的每个标签数组中只有一个项目被打印。 例如,如果数组是[1,2,3]然后转换为[Css,Js,HTML] ,则仅显示 Css 。 我该如何解决这个问题?

编辑:


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

  return [jobs, locations, departments, tags]
}

您从 promise.all 收到的数据将具有相同 jobId 的多个标签,因此您不能直接合并该 object,而是需要对其进行处理以将其转换为 objectId 到标签数组映射

  const dData = await Promise.all(tPromises)
  const tags = dData.reduce((acc, item) => {
      const [key, value] = Object.entries(item)[0];
      if(acc[key]) {
         acc[key].push(value);
      } else {
         acc[key] = [value];
      }
      return acc;
  }, {})
  setTags(prev => ({...prev, ...tags}))

一旦你这样做了,你可以在标签上 map 并渲染它们

   {tags[job.id] && tags[job.id].map(tag => <Col key={tags[job.id].id}>Tags:{tag.name} </Col>)}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM