反应验证不适用于插座
因此,我从后端通过套接字接收数据,然后将数据(项目)推向数组,但是如果变量为真(表示其暂停),我不想将项目推到数组。
const [sales, setSales] = useState([])
const [paused, setPaused] = useState(false);
const handlePush = (dt) => {
if(paused) return;
let data = dt.itemListed.data
let obj = {
name: dt.itemListed.data.item.metadata.name,
data
}
if (sales.findIndex(i => i.name === dt.itemListed.data.item.metadata.name) > 0) return;
if (sales.length >= 10) sales.pop();
setSales(prevState => [obj, ...prevState])
}
useEffect(() => {
socket.on("itemListed", (dt) => {
handlePush(dt);
})
}, [socket])
变量暂停设置为True,IM已经调试了它,我还在屏幕上显示了一个文本,说它是否暂停。另外,我检查数组大小是否为10的代码也无法正常工作。
该代码工作正常,但后来我更改为socket.io-client lib,它停止工作。
我认为正在发生的事情是,使用效应仅是“读”一次,它忽略了期货验证,它一直在推动项目。
我能做些什么?
so I receive data through socket from backend and then I push the data (item) to an array, but If a variable is true (means its paused) I dont want to push the item to the array.
const [sales, setSales] = useState([])
const [paused, setPaused] = useState(false);
const handlePush = (dt) => {
if(paused) return;
let data = dt.itemListed.data
let obj = {
name: dt.itemListed.data.item.metadata.name,
data
}
if (sales.findIndex(i => i.name === dt.itemListed.data.item.metadata.name) > 0) return;
if (sales.length >= 10) sales.pop();
setSales(prevState => [obj, ...prevState])
}
useEffect(() => {
socket.on("itemListed", (dt) => {
handlePush(dt);
})
}, [socket])
The variable paused is set to true, Im already debugging it and I have also a text displaying on the screen saying if its paused or not. Also, the code where I check if the array size is 10 is also not working.
The code was working fine, but then I changed into socket.io-client lib, and it stopped working.
What I think is happening is that the useEffect is being "read" only once and it is ignoring the futures validations and it keeps just pushing the items.
What can I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该解决您的问题
您的使用效果是在使用旧的
puse
值的先前版本的handlepush上聆听,因此这就是为什么它仍然能够推动的原因。如果添加函数
handlepush
作为使用效果的依赖性,则每次handerpush更改都会重新运行,因此您将拥有最新的函数。为了进行性能,您还应使用
usecallback(usecallback()
handlepush()
函数上的挂钩。This should fix your issue
Your useEffect is listening on a previous version of handlePush that uses the old
pause
value, so that's why it still able to push.If you add the function
handlePush
as a dependency for useEffect it would re-run every time handlePush changes so you would have the latest function.For performance, you should also utilize the
useCallback()
hook on thehandlePush()
function.