关于React Native useState的问题
来源:8-1 本章目标
慕尼黑0536602
2022-07-27
hi 老师,
我正尝试使用socket.io来更新收到的notification .
但是这里我遇到一个问题,我需要把之前收到的消息都能够保存起来。我用的是TypeScript,然后以下的这段代码,我无论如何,notficationCount的list都为空。。能帮我看下是什么问题吗?谢谢!
前端 Client:
1.首先我把socket 用 useContext 装起来,便于全局使用:
import React from 'react';
import socketio from 'socket.io-client';
export const socket = socketio.connect(SOCKET_URL);
export const SocketContext = React.createContext();
2.接着,当我发送一个像点赞的消息之后,对方可以收到我的通知,备注的地方就是出问题的点,前端:
import {SocketContext} from '../../auth/context';
import React, {useEffect, useState, useContext, useLayoutEffect} from 'react';
const Home = () =>{
const {socket, user} = useContext(SocketContext);
const [notificationCount, setNotificationCount] = useState([]);
const [me, setMe] = useState({});
// init data
const initialData = async () => {
try {
const meResult = await fetchGetMe();
setMe(meResult?.data.data);
} catch (error) {
console.log('initial data发生错误:', error);
}
};
useLayoutEffect(() => {
initialData();
}, []);
//get feedback from socket
useEffect(() => {
socket.on('getNotification', data => {
setNotificationCount(pre=> [...pre, data]); //就是这里出了问题。。
console.log('现在获取到的notification data :', notificationCount);
});
return () => {
socket.off('getNotification');
};
}, [socket]);
const onPressLike = ()=>{
socket.emit('sendNotification', {
senderUserId: me?.userId,
senderName: me?.userName,
receiverUserId: 123456, //我瞎编的,为了不让代码那么长..
type: 0, // 0:like 1.gifts 2.sunflower
});
}
<Button onClick={onPressLike}>点赞</Button>
}
后端的socket :
let onlineUsers = [];
const addUsers = (userId, socketId) => {
!onlineUsers.some((m) => m.userId !== userId) &&
onlineUsers.push({ userId, socketId });
};
const removeUser = (socketId) => {
onlineUsers = onlineUsers.filter((user) => user.socketId !== socketId);
};
const getUser = (receiverId) => {
return onlineUsers.find((m) => m.userId === receiverId);
};
io.on("connection", (socket) => {
console.log("有人连接上了");
socket.on("newUser", (userId) => {
addUsers(userId, socket.id);
console.log("现在的onlineUsers:", onlineUsers);
});
socket.on(
"sendNotification",
({ senderUserId, senderName, receiverUserId, type }) => {
console.log(
`收到senderName:${senderName},receiverID:${receiverUserId};type:${type},socketId:${socket.id};senderUserId:${senderUserId}`
);
console.log("sendNotification之后,现在的onlineUsers:", onlineUsers);
let receiver = {};
if (onlineUsers.length > 0) {
receiver = getUser(senderUserId);
console.log("此时的receiver是:", receiver);
io.to(receiver.socketId).emit("getNotification", {
senderName,
type,
});
} else {
receiver = null;
console.log("此时的receiver是:", receiver);
socket.emit("getNotification", { receiver });
}
}
);
socket.on("disconnect", () => {
console.log("有人下线了");
});
});
写回答
1回答
-
CrazyCodeBoy
2022-07-28
建议开启debug模式,然后在关键的地方打下debugger,断点调试一下看问题出在哪里012022-07-28
相似问题