简体   繁体   中英

React app not re-rendering after infinite scroll implementation

Hi guys hoping someone can help me with an issue. I built a function that fetches user posts from backend and returns them as a response:

const [posts, setPosts] = useState([]);

const newsFeed = async () => {
await axios
  .post(`${process.env.REACT_APP_API}/news-feed`)
  .then((res) => {
    setPosts(res.data);
  })
  .catch((err) => {
    console.log(err);
  });
};

This function gets called by useEffect and also whenever a post is submitted, liked, commented on etc. so that users' posts are always re-rendered every time they are modified or added.

It was working fine until I decided to implement Infinite Scroll to my application. I installed the npm package react-infinite-scroll-component and modified my function to look like this:

const [posts, setPosts] = useState([]);
const [page, setPage] = useState(1);

const newsFeed = async () => {
await axios
  .post(
    `${process.env.REACT_APP_API}/news-feed/${page}`)
  .then((res) => {
    let newPosts = posts;
    newPosts = newPosts.concat(res.data);
    setPosts(newPosts);
    setPage(page + 1);
  })
  .catch((err) => {
    console.log(err);
  });
};

The infinite scroll is working just fine but now the posts are not being re-rendered every time this function gets called and instead I need to refresh the page to see changes. I tried resetting the state of page back to 1 again on my postSubmit / likeHandler functions but this didn't have any effect. I'm not seeing any errors in the console so am unsure what is going on.

Replace let newPosts = posts; with let newPosts = [...posts]; Passing the same array reference to setState will not cause an update, since the value hasn't changed. By using [...posts] , you are creating a new array, causing the component to update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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