我有一个场景,用户可以使用拖放功能上传文件.
我将效果与空的空缺数组配合使用来设置RXJS订阅,该订阅处理已删除的文件和上载时间:
const [attachments, setAttachments] = useState([])
useEffect(() => {
...
fileUploadSubject.subscribe(newAttachments => {
setAttachments([...attachments,newAttachments])
})
...
return () => {
subscriptions.forEach(s => {
s.unsubscribe()
})
}
},[])
问题在于效果与附件以及setAttachments函数有关.
如果我将附件添加到依赖项数组,我将退订现有的上载内容.此外,由于其关闭,附件状态不会在效果内更新.
我该如何解决这样的情况?我想到了多种方法,但似乎找不到简单的方法.
解决方法:
useState的setState函数支持functional updates形式:
const [attachments, setAttachments] = useState([])
useEffect(() => {
...
const subscription = fileUploadSubject.subscribe(newAttachments => {
setAttachments((oldAttachments) => [...oldAttachments, newAttachments])
})
...
return () => subscription.unsubscribe()
}, [setAttachments, fileUploadSubject])
在依赖关系列表中可以省略永不更改的功能(即,在此两者都可以),但是我更愿意列出它们,以免忘记某些依赖关系.坚韧有eslint rules.