最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React useEffect doesn't trigger sometimes when I update my list as its dependency - Stack Overflow

programmeradmin5浏览0评论
const mylist = [1,2,3,4,5];
useEffect(() => {
console.log(mylist)
}, [mylist])

This is part of my code. useEffect doesn't trigger when I append a new element to mylist, but it does when I delete an element.

How do I fix it so that it triggers when I append new elements to mylist

I have a button doing onClick(e => mylist.push(e))
and another one onClick(e => mylist.remove(e))

const mylist = [1,2,3,4,5];
useEffect(() => {
console.log(mylist)
}, [mylist])

This is part of my code. useEffect doesn't trigger when I append a new element to mylist, but it does when I delete an element.

How do I fix it so that it triggers when I append new elements to mylist

I have a button doing onClick(e => mylist.push(e))
and another one onClick(e => mylist.remove(e))

Share Improve this question edited Jan 3, 2020 at 20:36 Emile Bergeron 17.4k5 gold badges85 silver badges131 bronze badges asked Jan 3, 2020 at 20:15 user12549070user12549070 1
  • 2 Show how you are appending and deleting to give some context – Brian Thompson Commented Jan 3, 2020 at 20:16
Add a ment  | 

5 Answers 5

Reset to default 4

The array that you're creating isn't being stored in state, so every render a new array is being created. The solution is to use react state:

function MyComponent() {
  const [myList, setMyList] = useState([0,1,2,3,4])

  useEffect(() => {
    console.log(myList)
  }, [myList])

  return (
   <div>
     {JSON.stringify(myList)}
     <button onClick={() => setMyList([...myList, myList.length])}>Add</button>
   </div>);
}



I couldn't make a ment on @Gerard's answer until I have more reputation points. I want to add that make sure you pass an arrow function to setMyList as shown:

function MyComponent() {
  const [myList, setMyList] = useState([0,1,2,3,4])

  useEffect(() => {
    console.log(myList)
  }, [myList])

  return (
   <div>
     {JSON.stringify(myList)}
     <button onClick={() => setMyList(prevList => [...prevList, prevList.length])}>Add</button>
   </div>);
}

It worked when I change the dependency to mylist.toString() I thought useEffect does deep parison on the second parameter

You could check the length of the array so if the array size changes the effect will be excecuted:

useEffect(() => {
  //Your effect  
}, [mylist.length])

useEffect using strict parison, but an array always es up as false, so [1] === [1] is false and [1] === [1, 2] is still false.

It likely only runs on first render, that is why it's not updating it when you add or remove from list. Try putting the length of the array as a dependancy and it'll work as you intend it to.

So,

useEffect(() => {
//stuff on myList
}, [myList.length])

So if you add something to it, it'll be paring integer to integer

发布评论

评论列表(0)

  1. 暂无评论