简体   繁体   English

使用 state 挂钩有条件地更新数组

[英]Using state hooks to conditionally update an array

I want to add items to an array with the useState hook instead of doing array.push.我想使用 useState 挂钩将项目添加到数组中,而不是执行 array.push。 This is the original code:这是原始代码:

   let tags = []
      data.blog.posts.map(post => {
        post.frontmatter.tags.forEach(tag => {
          if (!tags.includes(tag)){
            tags.push(tag)
          }
        })
      })

This is one of several things I've tried with React:这是我用 React 尝试过的几件事之一:

const [tags, setTags] = useState([])
  
  data.blog.posts.map(post => {
    post.frontmatter.tags.map(tag => {
      if (!tags.includes(tag)){
        setTags(tags => [...tags, tag])
      }
    })
  })

The "tags" state variable does not receive anything in the above example. “标签” state 变量在上面的示例中没有收到任何内容。

I have looked at a variety of similar threads but the problems and solutions there are difficult to translate to this situation.我查看了各种类似的线程,但那里的问题和解决方案很难转化为这种情况。

Try something like this.尝试这样的事情。 I would not add a setState inside a loop since you will trigger a regender every time you add something to it.我不会在循环中添加 setState,因为每次向其中添加内容时都会触发重新生成器。

const [tags, setTags] = useState([])

const myTags = []
data.blog.posts.map(post => {
    if (!tags.includes(tag)) {
        myTags.push(tag)
    }
})
setTags([...myTags])

You can try setting the tags state in initial render or on any event as per your requirement.您可以尝试在初始渲染中或根据您的要求在任何事件中设置标签 state。

const [tags, setTags] = useState([]);

useEffect(()=>{
  const arr=[];
  data.blog.posts.map(post => {
    post.frontmatter.tags.map(tag => {
      if (!arr.includes(tag)){
        arr.push(tag)
      }
    })
  });
 setTags([...arr]);
},[]);

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

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