js组件中的无限控制台日志记录

js组件中的无限控制台日志记录

本文介绍了React.js组件中的无限控制台日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用自己的MERN应用,当我在NewsPage组件中记录smth时,它会无限记录.

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

NewsPage组件:

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);

获取新闻操作:

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?

推荐答案

实际上,您使用的 useEffect 错误.

Actually, you have wrong useEffect usage.

每次组件收到新道具时都会调用效果,因此,它看起来像这样:

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

1)组件安装,从 useEffect
调用函数2)进行API调用,更新存储区中的数据
3)数据传递到容器,更新哑巴"组件
4)Dumb组件进行重新渲染,从 useEffect 调用func,这就是无限循环.

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)添加一些条件渲染.我很确定,您只需要在初始加载时调用它即可.
2)添加类似 ImmutableJS 的东西,它不会重新渲染组件,并且如果没有任何变化也不会改变存储空间

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

这篇关于React.js组件中的无限控制台日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 09:28