由于我的 currentUser 状态变量是在 useEffect 中设置的,并且 getJoinRoom 需要 currentUser 所以我在 getJoinRoom 上设置 useCallback 并具有依赖 currentUser 状态,但似乎在调用 getJoinRoom 时仍没有设置 currentUser
连接 TypeError 错误:无法读取未定义的属性“getJoinableRooms”
function App() {
const [messages, setMessages] = useState([]);
const [currentUser, setCurrentUser] = useState();
const [joinableRooms, setJoinableRooms] = useState([]);
const [joinedRooms, setJoinedRooms] = useState([]);
const sendSimpleMessage = (text) => {
// send simple text
currentUser.sendSimpleMessage({
text: text,
roomId: '7b7a1d23-e869-4c19-8eab-e88d5144dd72'
});
}
const subscribeToRoom = (roomId) => {
setMessages([]);
currentUser.subscribeToRoomMultipart({
// roomId: '7b7a1d23-e869-4c19-8eab-e88d5144dd72',
roomId: roomId,
hooks: {
onMessage: message => {
// console.log('message object: ', message.parts[0].payload.content);
setMessages(prevMessages => [...prevMessages, message]);
}
}
})
};
const getJoinRoom = useCallback(() => {
currentUser.getJoinableRooms()
.then(joinableRooms => {
setJoinableRooms(joinableRooms);
setJoinedRooms(currentUser.rooms);
}).catch(err => {
console.log('Error on getting joinable rooms', err);
});
}, [currentUser])
useEffect(() => {
const chatManager = new ChatManager({
instanceLocator: instanceLocator,
userId: 'Henry',
tokenProvider: new TokenProvider({
url: tokenUrl
})
});
chatManager.connect()
.then(currUser => {
setCurrentUser(currUser);
//currUser.getJoinableRooms()
// .then(joinableRooms => {
// setJoinableRooms(joinableRooms);
// setJoinedRooms(currUser.rooms);
// }).catch(err => {
// console.log('Error on getting joinable rooms', err);
// });
getJoinRoom();
}).catch(err => {
console.log('Error on connection', err)
})
}, [getJoinRoom]);
return (
<div className="app">
<RoomList
rooms={[...joinableRooms, ...joinedRooms]}
subscribeToRoom={subscribeToRoom}
/>
<MessageList messages={messages} />
<SendMessageForm sendSimpleMessage={sendSimpleMessage} />
<NewRoomForm />
</div>
);
}
export default App;