reactjs - 如何避免由于组件渲染多少时间而无法从后端获取数据到前端?
问题描述
问题,我正在创建这个名为对话的组件,对话组件将根据用户与另一个用户的许多对话呈现。渲染后,它将传递一个道具以在名为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>
</>
);
};
输出: 约翰·多伊,约翰·罗伯特
解决方案
我可以试试这个
useEffect(() => {
// to do
}, []);
推荐阅读
- android - 如何在 xml 中为此 FAB 提供相等的空格?
- c++ - % 在变量旁边的代码中是什么意思?
- c# - Angular 6 不显示从 Asp Net Web API 2.2 检索到的数据
- python - 为什么 PyYAML/ruamel 在 Python 2 上结合转义代理?
- c# - 如何在 .netcore/Linux 中实现 Diffie Hellman
- tensorflow - C++中的Tensorflow:成功读取LSTM编码器解码器模型的协议缓冲区
- dart - Dart 类型别名
- typo3 - Typo3 用本地文件夹路径中的大数据 URL 替换大外部图像的 src
- android - 重新创建应用程序实例时,getApplicationContext() 返回 null
- mongodb - 如何使用 mongodb 查询订购和检索数据?