node.js - 更新保存在我前端数组中的数据
问题描述
这里的问题是我从后端带来了我的朋友列表并将其存储在前端的一个数组中以便我可以使用它但是当我的朋友列表中的用户更新他的图片时它没有在我的列表中更新所以这里的挑战对我来说,我想要一种方法来更新数组中的这些数据我想出了一种方法,但它只能在点击时工作,所以这对于良好的用户体验是不可接受的,这应该是动态的,我也尝试过 socket io,但这个数据已经存储在我的数组中,所以我看不到套接字在这方面会有用,任何人都面临过这样的问题,如果有更好的方法请告诉我,我使用 react、redux、mongodb 和 Node
exports.getFriendList = async (req, res) => {
try {
let user = req.user;
const myFriendList = await Friend.findOne({ user: user.id });
io.emit('get friend', myFriendList);
res.json(myFriendList);
} catch (err) {
console.error(err.message);
res.status(500).json({ msg: err.message });
}
};
这就是数据来自数据库的方式,其他用户更新后,跟随者和跟随数组保持不变图像我尝试使用套接字 io 作为测试更新我的图像后获取我的朋友列表,但它不起作用
解决方案
如果您希望图像在更新时在前端自动更新,Socket.io(或类似的 websocket 库)正是您所需要的。
您的目标是建立侦听器以更新个人资料图像,并向侦听该事件的人发送消息。
您似乎非常关心前端数组中已经存在的图像,但是没有理由在初始化后不能修改数组。
为了争论,你的发射可能是这样的:
app.post(`/api/update-avatar`, function (req, res) => {
//Deal with updating the image here
//............
//Then emit the image
io.emit(`user-image-updated`, {userId: 2, userAvatar: yyyyyyyyy})
})
您的前端侦听器可能如下所示:
const FriendList = (props) => {
const [friends, setFriends] = React.useState([
{ userId: 1, userAvatar: null, userId: 2, userAvatar: null },
]);
socket.on(`user-image-updated`, (data) => {
setFriends((currentListOfFriends) => {
return currentListOfFriends.map((eachFriend) => {
if (eachFriend.userId == data.userId) {
return data;
} else {
return eachFriend;
}
});
});
});
return (
<ul>
{friends.map((friend) => (
<li>
<img src={friend.userAvatar} />
</li>
))}
</ul>
);
};
推荐阅读
- java - 如何读取 CSV 文件的第一列
- c# - 仅在代码窗口打开时启用我的 Visual Studio 扩展的菜单项
- nlp - Gensim 关键字,如何加载德国模型?
- c# - 在 BotFramework v4 中从不调用 OAuthPrompt
- c - C 编程 - 结构内的整数值在赋值后变为“随机”
- android - Room and ViewModel, multiple queries?
- javascript - js 文件路径在正确的方向,但在主题中没有响应
- vim - 将密钥附加到 vim 中的早期记录
- java - 使用visual studio code ion ubuntu构建java代码时出现错误?
- amazon-web-services - AWS ECS Fargate 从跨账户 ECR 存储库中提取映像