首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >“未处理的拒绝(错误):太多的重新呈现.”因为我在循环中设置状态?

“未处理的拒绝(错误):太多的重新呈现.”因为我在循环中设置状态?
EN

Stack Overflow用户
提问于 2021-10-29 01:19:51
回答 2查看 58关注 0票数 0

我得到了一个“未处理的拒绝(错误):太多的重新呈现。反应限制呈现的数量,以防止无限循环。”以下代码的消息。不知道是什么导致了这个问题。

我认为这是因为我在users.map循环中调用了users.map。但是,如果我将setNewNotifications(combineLikesCommentsNotifications)移出循环之外,它将无法再读取likeNewNotifications / commentNewNotifications。最好的方法是什么?

下面的代码,对于上下文,users返回:

代码语言:javascript
复制
const users = [
  {
    handle: "BEAR6",
    posts: undefined,
    uid: "ckB4dhBkWfXIfI6M7npIPvhWYwq1"    
  },
  {
    handle: "BEAR5",
    posts: [
      {
        comment: false,
        handle: "BEAR5",
        key: "-Mmx7w7cTl-x2yGMi9uS",
        like: {
          Mn4QEBNhiPOUJPBCwWO: {
            like_notification: false,
            postId: "-Mmx7w7cTl-x2yGMi9uS",
            postUserId: "rFomhOCGJFV8OcvwDGH6v9pIXIE3",
            uid: "ckB4dhBkWfXIfI6M7npIPvhWYwq1",
            userLikeHandle: "BEAR6"
        }},
        post_date: 1635260810805,
        title: "hello"
      },
      {
        comment: false,
        comments_text: {0: {
          comment_date: 1635399828675,
          comment_notification: false,
          commenter_comment: "hi1",
          commenter_handle: "BEAR6",
          commenter_uid: "ckB4dhBkWfXIfI6M7npIPvhWYwq1",
          key: "-Mn4QF1zT5O_pLRPqi8q"
        }},
        handle: "BEAR5",
        key: "-MmxOs0qmFiU9gpspEPb",
        like: {
          Mn4QDCOrObhcefvFhwP: {
            like_notification: false,
            postId: "-MmxOs0qmFiU9gpspEPb",
            postUserId: "rFomhOCGJFV8OcvwDGH6v9pIXIE3",
            uid: "ckB4dhBkWfXIfI6M7npIPvhWYwq1",
            userLikeHandle: "BEAR6"}, 
          Mn4QKEk95YG73qkFsWc: {
            postId: "-MmxOs0qmFiU9gpspEPb",
            postUserId: "rFomhOCGJFV8OcvwDGH6v9pIXIE3",
            uid: "rFomhOCGJFV8OcvwDGH6v9pIXIE3",
            userLikeHandle: "BEAR5"
           }},
        post_date: 1635265250442,
        title: "hi" 
      }
    ],
    uid: "rFomhOCGJFV8OcvwDGH6v9pIXIE3"    
  }
]

代码语言:javascript
复制
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';


export default function Notifications() {
  const [newNotifications, setNewNotifications] = useState('')

  const users = useSelector(state => state.users)

  return users.map((post) => {


      if(post.posts){
        return post.posts.map((postContent) => {
          const likes = postContent.like ? Object.values(postContent.like) : null
          const comments = postContent.comments_text ? Object.values(postContent.comments_text) : null

          const likeNewNotifications = likes ? likes.filter(post => {
            return post.like_notification === false
          } ) : null

          const commentNewNotifications = comments ? comments.filter(post => {
            return post.comment_notification === false
          } ) : null

          const combineLikesCommentsNotifications = likeNewNotifications.concat(commentNewNotifications)
          setNewNotifications(combineLikesCommentsNotifications)
        }
        )
}

    return (
      <div>
          <p>
              {newNotifications}
          </p>
      </div>
    );
 }
)
}
EN

回答 2

Stack Overflow用户

发布于 2021-10-29 01:34:26

有多个错误。但是让我们一步一步地面对它。

我将复制和粘贴您的代码,但添加额外的注释,以使您知道我所引用的位置:

代码语言:javascript
复制
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';


export default function Notifications() {
  const [newNotifications, setNewNotifications] = useState('')

  const users = useSelector(state => state.users)

  // Step 0: I guess the error is because this users.map is running everytime (with any update in the component. So, when you set a new state, it'll render again. So, you have to do this, probably 2 times: on mount and after one update. 

  // Step 1: You're using users.map but it returns a new array. My recommendation would be: use users.forEach instead.
  return users.map((post) => {


      if(post.posts){
        return post.posts.map((postContent) => {
          const likes = postContent.like ? Object.values(postContent.like) : null
          const comments = postContent.comments_text ? Object.values(postContent.comments_text) : null

          const likeNewNotifications = likes ? likes.filter(post => {
            return post.like_notification === false
          } ) : null

          const commentNewNotifications = comments ? comments.filter(post => {
            return post.comment_notification === false
          } ) : null

          const combineLikesCommentsNotifications = likeNewNotifications.concat(commentNewNotifications)
          setNewNotifications(combineLikesCommentsNotifications)
        }
        )
}

    return (
      <div>
          <p>
              {newNotifications}
          </p>
      </div>
    );
 }
)
}

(将步骤0和步骤1作为代码中的注释阅读),也是关于:

但是如果我将setNewNotifications(combineLikesCommentsNotifications)移出循环之外,它就不能再读取likeNewNotifications / commentNewNotifications了。最好的方法是什么?

您可以执行步骤3:,您可以使用let,在循环的父级中设置一个变量,并更新循环中的值(如果有数组,即使是const,也可以推送)。就像:

代码语言:javascript
复制
function foo() {
  const users = [{}, {}, {}, {}];
  const usersWithEvenId = [];

  users.forEach(user => {
    if (user.id % 2 === 0) {
      usersWithEvenId.push(user)
    }
  })
}

考虑到这三个步骤,得到的代码如下:

代码语言:javascript
复制
import React, { useState, useEffect} from 'react';
import { useSelector, useDispatch } from 'react-redux';

export default function Notifications() {
  const [newNotifications, setNewNotifications] = useState('');
  const users = useSelector(state => state.users);

  // Function to get new posts
  const getNewPosts = () => {
    const notifications = [];
    users.forEach((user) => {
      if (user.posts) {
        posts.forEach((post) => {
          // Your logic;
          notifications.push(newNotifications)
        })
      }
    });
    setNewNotifications(notifications);
  };

  // Run to get newPosts on mount (but also in any other moment)
  useEffect(() => {
    getNewPosts();
  }, [])

  return (
    <div>
      <p>
        {newNotifications}
      </p>
    </div>
  );
}
票数 1
EN

Stack Overflow用户

发布于 2021-10-29 01:51:59

也许您可以这样编写代码:

代码语言:javascript
复制
import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";

export default function Notifications() {
  const users = useSelector((state) => state.users);

  const combineLikesCommentsNotifications = users.map((post) => {
    if (post.posts) {
      return post.posts.map((postContent) => {
        const likes = postContent.like ? Object.values(postContent.like) : null;
        const comments = postContent.comments_text
          ? Object.values(postContent.comments_text)
          : null;

        const likeNewNotifications = likes
          ? likes.filter((post) => {
              return post.like_notification === false;
            })
          : null;

        const commentNewNotifications = comments
          ? comments.filter((post) => {
              return post.comment_notification === false;
            })
          : null;

        const combineLikesCommentsNotifications = likeNewNotifications.concat(
          commentNewNotifications
        );
        setNewNotifications(combineLikesCommentsNotifications);
      });
    }else{
      return [];
    }
  })

  const [newNotifications, setNewNotifications] = useState(combineLikesCommentsNotifications);


  return (
    <div>
      <p>{newNotifications}</p>
    </div>
  ); ;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69762585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档