猿问

使用长时间运行的任务和合并状态来反应useEffect挂钩

我有一个场景,用户可以使用拖放功能上传文件。


我将效果与空的空缺数组配合使用来设置RXJS订阅,该订阅处理已删除的文件和上载时间:


const [attachments, setAttachments] = useState([])


useEffect(() => {

    ...

    fileUploadSubject.subscribe(newAttachments => {

       setAttachments([...attachments,newAttachments])

    })

    ...

    return () => {

      subscriptions.forEach(s => {

        s.unsubscribe()

      })

    }

},[])


问题是效果attachments与setAttachments功能以及功能都息息相关。


如果添加attachments到依赖项数组,我将退订现有的上载。另外,attachment状态由于其关闭而不会在效果内部更新。


我该如何解决这样的情况?我想到了多种方法,但似乎找不到简单的方法。


手掌心
浏览 125回答 2
2回答

一只斗牛犬

setState函数useState支持功能更新形式:const [attachments, setAttachments] = useState([])useEffect(() => {    ...    const subscription = fileUploadSubject.subscribe(newAttachments => {       setAttachments((oldAttachments) => [...oldAttachments, newAttachments])    })    ...    return () => subscription.unsubscribe()}, [setAttachments, fileUploadSubject])可以从不更改的功能(即此处两个功能)可以在依赖项列表中省略,但是我更喜欢列出它们,以免忘记某些依赖项。对此有严厉的规定。

白衣染霜花

如果我将附件添加到依赖项数组,我将退订现有的上载不确定为什么取消订阅,不熟悉 fileUploadSubject.subscribe另外,由于关闭状态,附件状态不会在效果内更新您可以useReducer代替useState,而无需依赖效果中的状态。也许是这样的:function reducer(state, action) {&nbsp; switch (action.type) {&nbsp; &nbsp; case "ADD_ATTACH":&nbsp; &nbsp; &nbsp; return [...state, action.payload];&nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; throw new Error();&nbsp; }}function App() {&nbsp; const [attachments, dispatch] = useReducer(reducer, []);&nbsp; useEffect(() => {&nbsp; &nbsp; // ...&nbsp; &nbsp; fileUploadSubject.subscribe(newAttachments => {&nbsp; &nbsp; &nbsp; dispatch({ type: "ADD_ATTACH", payload: newAttachments });&nbsp; &nbsp; });&nbsp; &nbsp; // ...&nbsp; &nbsp; return () => {&nbsp; &nbsp; &nbsp; subscriptions.forEach(s => {&nbsp; &nbsp; &nbsp; &nbsp; s.unsubscribe();&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; };&nbsp; }, [/*fileUploadSubject?,&nbsp; subscriptions? */]);&nbsp; return <div>{ /* some UI */ }</div>;}我仍然认为您的效果不依赖任何东西是很奇怪的,请确保subscriptions并且fileUploadSubject确实不应该将其放置在dependencies数组内。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答