[英]ReactJS callback useEffect hook
While by following the documentation of GetStreamIO service I am trying to hide the channel message when a user connects to the channel, so that the previous message history will not be shown to a user.通过遵循 GetStreamIO 服务的文档,我试图在用户连接到频道时隐藏频道消息,以便不会向用户显示之前的消息历史记录。
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;
I am going to hide the messages through channel.hide()
method after the state value of channel
is updated, but this line throws an error of Uncaught (in promise) TypeError: Cannot read property 'hide' of null
在更新channel
的 state 值后,我将通过channel.hide()
方法隐藏消息,但是此行会引发Uncaught (in promise) TypeError: Cannot read property 'hide' of null
The setChatClient
function is async. setChatClient
function 是异步的。 It is posible that when channel.hide()
runs, the channel value is null.可能当channel.hide()
运行时,通道值为 null。 I recommend you to hide the channel when it's value has changes:我建议您在值发生变化时隐藏通道:
useEffect(() => {
if(channel) channel.hide();
}, [channel]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.