在遵循 GetStreamIO 服务的 documentation 时,我试图在用户连接到频道时隐藏频道消息,以便不会向用户显示之前的消息历史记录。
const App = () => {
const [chatClient, setChatClient] = useState(null);
const [channel, setChannel] = useState(null);
useEffect(() => {
const initChat = async () => {
const client = StreamChat.getInstance(env.API_KEY);
const _channel = await client.channel('livestream', env.ROOM_NAME);
setChatClient(client);
setChannel(_channel)
};
initChat();
}, []);
useEffect(() => {
const hideChat = async () => {
if(channel !== null) {
console.log(channel);
await channel.hide();
}
}
hideChat();
}, [channel])
return (
<Chat client={chatClient}>
<Channel channel={channel}>
<Window>
<VirtualizedMessageList />
</Window>
</Channel>
</Chat>
);
};
export default App;
我打算在channel.hide()
的状态值更新后通过channel
方法隐藏消息,但是这一行抛出了Uncaught (in promise) TypeError: Cannot read property 'hide' of null
的错误
答案 0 :(得分:0)
setChatClient
函数是异步的。当 channel.hide()
运行时,通道值为空是可能的。我建议您在频道值发生变化时隐藏频道:
useEffect(() => {
if(channel) channel.hide();
}, [channel]);