Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.8k views
in Technique[技术] by (71.8m points)

我不能理解redux无法处理异步状态这个说法

我的理解是,redux-thunk或redux-saga的出现只是为了把异步业务代码从组件剥离,而并非解决redux无法处理异步状态问题的把?

纯redux使用中,完全可以在useEffect调用接口,并在回调函数中dispatch同步action,

import {fetchUser} from './services'
import {saveUser} from './actions'

function App({dispatch}) {
    useEffect(() => {
        fetchUser().then(res => dispatch(saveUser(res.user)))
    }, [])
}

相比较纯redux,redux-thunk只不过把调用接口封装成了一个异步action creator而已啊,

import {fetchUser} from './services'
import {saveUser} from './actions'

function saveUserAsync() {
    return function (dispatch) {
        fetchUser().then(res => dispatch(saveUser(res.user)))
    }
}
function App({dispatch}) {
    useEffect(() => {
        dispatch(saveUserAsync())
    }, [])
}

redux-saga和redux-thunk类似,只不过用的是generater函数而已。

我想请教一下,我这么理解有什么问题吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

无法处理异步指的是reducer内不能处理异步,因为规定reducer要为纯函数,不能有副作用
像redux-thunk是增强dispatch的能力,你dispatch特定的东西会先由redux-thunk中间件处理,然后再合适的条件下再去dispatch实际的action调用reducer去处理
像你这种在useEffect去处理副作用(异步请求)就和redux无关了,和redux无法处理异步状态并不矛盾


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...