使用redux-thunk完成异步connect的第二个参数的对象写法。

redux-thunk

使用redux-thunk完成异步connect的第二个参数的对象写法。


redux-thunk它是由redux官方开发出来的redux中间件
它的作用:解决redux中使用异步处理方案。redux-thunk中间件可以允许在connect参数2中派发任务时返回的是一个函数,此函数形参中,redux-thunk会自动注入一个dispatch派发函数,从而让你调用dispath函数来派发任务给redux,从而实现异步处理。
在这里插入图片描述
用法:
说白了就是解决connect
第二个参数
传入一个对象时不能对其进行异步操作也方便了模块化

  • action.js模块文件
  • 返回一个对象,通过中间件函数来异步操作dispatch
export const add = (n=4) =>async dispatch =>{
    
    
    let users = await get('/api/v1/getNowPlayingFilmList?cityId=110100&pageNum=1&pageSize=10');
    console.log("users_______",users);
    dispatch({
    
    type:"add",payload:n})
}
  • connect.js文件
import * as action from  "@/store/count/countAction"
这个action就是一个对象:{
    
    add:function(){
    
    }}
***************************
注意第二个参数
export default connect(mapStateToProps, action)

在设置一个type类型的js文件;

export const ADD = "add"

在这里插入图片描述
避免过多的使用的不同的类型名。然后再去模块化。


策略模式:

完成reducer方法的改造:
又可以完成对reducer的函数的优化
各个 mutations的封装后加入状态 执行过程封装成了过程性。
说白了就是把reducer的mutations

const mutations = {
    
    
    [ADD](state,data){
    
    
        return {
    
    
            ...state,
            num:state.num+data
        }
    }
}
const reducer = (state=initState,action)=>{
    
    
    if(mutations[action.type]){
    
    
        return mutations[action.type](state,action.payload)
    }
    return state
}

猜你喜欢

转载自blog.csdn.net/m0_46672781/article/details/127128716