请问在redux中的中间件thunk主要有什么作用?

redux中的中间件thunk主要有什么作用


素胚勾勒不出你
浏览 522回答 3
3回答

www说

thunk的意思是中间函数,在redux中,有个东西叫做action,如果配置了redux-thunk,那么在action中写代码的时候,就可以写成下面这种形式:function saveData(data) {return {type: 'SVAE_DATA',date: data}}exports function getData(){return async (dispatch) => {const data = await get(`/api`)if (result) {await dispatch(saveData(data))}}}在这个例子中,saveData就是一个thunk,getData的作用是接收服务端返回的数据,然后通过thunk函数去调用对应的reducers保存到store上。dispatch就是负责调用thunk函数

慕斯709654

执行阶段dispatch(action) 等于 composedABC(action) 等于执行 function A(action) {...}在函数 A 中执行 next(action), 此时 A 中 next 为 composedBC,那么等于执行 composedBC(action) 等于执行function B(action){...}在函数 B 中执行 next(action), 此时 B 中 next 为 composedC,那么等于执行 composedC(action) 等于执行function C(action){...}在函数 C 中执行 next(action), 此时 C 中 next 为 store.dispatch 即 store 原生的 dispatch, 等于执行store.dispatch(action)store.dispatch 会执行 reducer 生成最新的 store 数据所有的 next 执行完过后开始回溯执行函数 C 中 next 后的代码执行函数 B 中 next 后的代码执行函数 A 中 next 后的代码整个执行 action 的过程为 A -> B -> C -> dispatch -> C -> B -> A

繁星淼淼

thunk的意思是中间函数,在redux中,有个东西叫做action,如果配置了redux-thunk,那么在action中写代码的时候,就可以写成下面这种形式:function saveData(data) {return {type: 'SVAE_DATA',date: data}}exports function getData(){return async (dispatch) => {const data = await get(`/api`)if (result) {await dispatch(saveData(data))}}}在这个例子中,saveData就是一个thunk,getData的作用是接收服务端返回的数据,然后通过thunk函数去调用对应的reducers保存到store上。dispatch就是负责调用thunk函数
打开App,查看更多内容
随时随地看视频慕课网APP