首页 > 解决方案 > 如何避免由于组件渲染多少时间而无法从后端获取数据到前端?

问题描述

问题,我正在创建这个名为对话的组件,对话组件将根据用户与另一个用户的许多对话呈现。渲染后,它将传递一个道具以在名为conversationList的对话的子组件上使用。我的问题是因为会话组件将基于 no 呈现。在对话中,conversationList 中的 dispatch 函数也会重新渲染。

Conversation.js <-- If the no. of conversation in the backed is 2 it will render 2 times.
<div className='bg-lightGrey p-8 flex flex-col'>
            <div className='w-full flex flex-row'>
              <div class='bg-white w-1/4 mr-6 p-6 flex flex-col rounded-lg'>
                {conversationInfo.map((conversation, index) => (
                  <ConversationList
                    key={index}
                    currentConversation={conversation}
                    currentUser={currentAccountInfo._id}
                  />
                ))}
              </div>
              <ChatBox
                socket={socket}
                roomId={roomId}
                user={currentAccountInfo}
              />
            </div>
          </div>

conversationList.js
    const ConversationList = ({ currentConversation, currentUser }) => {
      const [userId, setUserId] = useState(null);
      const dispatch = useDispatch();
    
      const accountGetById = useSelector((state) => state.accountGetById);
      const { accountById } = accountGetById;
    
      useEffect(() => {
        const friendId = currentConversation.members.find(
          (id) => id !== currentUser
        );
    
        if (!accountById) {
          dispatch(getAccountById(friendId));
        }
    setUserId(accountById);
      }, [currentUser, accountById]);
    
      return (
        <>
        <div className='w-full'>
    <div className='mb-6 flex cursor-pointer'>
      <div className='relative'>
        <img
          className='mr-4 rounded-full'
          src={userId && userId.accountProfileUploaded}
          alt={userId && `${userId.firstName} ${userId.lastName}`}
          title={userId && `${userId.firstName} ${userId.lastName}`}
          style={{
            width: '42px',
            height: '42px',
          }}
        />
      </div>
      <p className='text-xs text-grey font-bold'>
        {userId && `${userId.firstName} ${userId.lastName}`}
      </p>
    </div>
  </div>
        </>
      );
    };

输出: 约翰·多伊,约翰·罗伯特

代码输出: John Doe、John Deo 在此处输入图像描述

标签: reactjs

解决方案


我可以试试这个

useEffect(() => {
    // to do
}, []);

推荐阅读