首页 > 解决方案 > 更新保存在我前端数组中的数据

问题描述

这里的问题是我从后端带来了我的朋友列表并将其存储在前端的一个数组中以便我可以使用它但是当我的朋友列表中的用户更新他的图片时它没有在我的列表中更新所以这里的挑战对我来说,我想要一种方法来更新数组中的这些数据我想出了一种方法,但它只能在点击时工作,所以这对于良好的用户体验是不可接受的,这应该是动态的,我也尝试过 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 作为测试更新我的图像后获取我的朋友列表,但它不起作用 在此处输入图像描述

标签: node.jsreactjsmongodbredux

解决方案


如果您希望图像在更新时在前端自动更新,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>
  );
};


推荐阅读