【发布时间】:2019-12-22 15:27:36
【问题描述】:
我正在构建一个基本的 Slack 克隆。所以我有一个“房间”,里面有多个“频道”。用户订阅了 Room 中的所有消息,但如果新消息是用户当前 Channel 的一部分,我们只会将它们添加到当前消息列表中
const [currentChannel, setCurrentChannel] = useState(null);
const doSomething = (thing) => {
console.log(thing, currentChannel)
}
useEffect(() => {
// ... Here I have a call which will grab some data and set the currentChannel
Service.joinRoom(roomId).subscribe({
next: (x) => {
doSomething(x)
},
error: (err: any) => { console.log("error: ", err) }
})
}, [])
我在这里只显示一些代码来说明我的问题。订阅是在currentChannel 更新之前创建的,这很好,因为我们想监听所有内容,然后根据currentChannel 有条件地渲染。
我遇到的问题是,即使currentChannel 设置正确,因为在useEffect 挂钩中定义next: 函数时它为空,doSomething 将始终记录currentChannel一片空白。我知道它设置正确,因为我在渲染的屏幕上显示它。那么为什么doSomething 以currentChannel 为空的方式限定范围呢?每次调用next 函数时,我怎样才能让它每次访问currentChannel 的最新状态时调用一个新函数?我尝试了 useState 以及从 redux 存储/检索它,但没有任何效果。
【问题讨论】:
标签: reactjs apollo react-apollo apollo-client