Infinite console logging in React.js component

与世无争的帅哥 提交于 2021-02-10 23:30:27

问题


I'm working on my MERN app, and when I'm logging smth in NewsPage component, it logs infinitely.

NewsPage component:

const NewsPage = ({news, fetchNews}) => {
  const postNews = (title, body) => {
    axios.post("http://localhost:9000/news", { title, body });
  }

  useEffect(() => {
    fetchNews();

  }, [fetchNews, postNews])

  return (
    <>
      <AddNewsForm postNews={postNews}/>
      <h1>News:</h1>
      <NewsItemPage news={news} />
    </>
  );
};

const mapStateToProps = state => ({
  news: state.news
})

export default connect(mapStateToProps, {fetchNews})(NewsPage);

Fetch news action:

export const fetchNews = () => dispatch => {
  fetchRequest();

  try {
    const fetch = async () => {
      const res = await axios.get("http://localhost:9000/news");

      dispatch({
        type: a.FETCH_NEWS_SUCCESS,
        payload: res.data
      });
    }
    fetch()
  } catch (e) {
    dispatch({
      type: a.FETCH_NEWS_FAILURE,
      error: e
    });
  }
}

It works correctly, I can fetch news from and post news to my backend, but if I log anything in console, it would be logging infinitely, and I will not get any error.

is there a way to fix this, and is this a real problem?


回答1:


Its likely because whatever function the console log is located in is being used in render, which itself is a loop. Otherwise, there is no other way that I can see why it would repeat. It probably won't end up being a problem, unless the code you are executing slows down, which might cause performance issues in the future.




回答2:


You're tracking fetchNews and postNews in your useEffect array, which will re-rerun fetchNews(); on every render.

Unless the values in the useEffect second argument are primitives, you need to use some deep compare methods for those: https://stackoverflow.com/a/54096391/4468021




回答3:


Actually, you have wrong useEffect usage.

Effect would be called each time when component receive new props, so, it looks like this:

1) Component mounts, call function from useEffect
2) It makes API call, update data in store
3) Data passed to container, updates "dumb" component
4) Dumb component makes re-rendering, calling func from useEffect, and that's infinity loop.

In fact, It is pretty weird that you don't have memory leak.
What you can do, is:

1) Add some conditional rendering. I pretty sure, you need to call it only on initial load.
2) Add something like ImmutableJS, it would not re-render component and would not mutate store if nothing has changed



来源:https://stackoverflow.com/questions/57171206/infinite-console-logging-in-react-js-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!