redux进一步优化

1. 将原来的  mapStateToDispatch  中的函数提取出来,放在组件中,

如原来的:

function mapStateToProps(state, ownProps) {
  return {
    hasMore:state.getIn(['tabs','hasMore']),
  }
}
function mapDispatchToProps(dispatch) {
  return {
    addTabList:(id,page,tabIndex) => {
      dispatch(actionCreators.addTabList(id,page,tabIndex)); //在actionCreator中使用dispatch发送
    }
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(Main);

改为:也就是所有的dispatch 放在actionCreator中

addTabList(id,page,tabIndex){
  actionCreators.addTabList(id,page,tabIndex);
}

export default connect(mapStateToProps, null)(Main);

对应的actionCreator:

原来是:

export const addTabList = (cardId,page,tabIndex) => {
    let currpage = page +1 ;
    return(dispatch)=>{
        dispatch(changeLoading(true));
        API.requestRightList(cardId,currpage,tabIndex).then(function (response) {
                dispatch(addList(response.result,currpage));
                dispatch(changeLoading(false));
        }) 
    }
};

改为:异步await 去掉 return dispatch ,引入store 使用 store.dispatch (原来是store在最外层组件中引入,则每个子组件都可以使用dispatch ,现在是把dispatch放在了actionCreator,所以要引入store)

若没有 请求其他接口的,只是单纯的派发数据:

import store from '../../../store';
export const changeFlag = () => {
    store.dispatch({
        type: actionType.CHANGE_MORE_FLAG
    })
}

否则的话:

export const addTabList = async(cardId,page,tabIndex) => {
    let currpage = page +1 ;
    store.dispatch(changeLoading(true));
    let response = await API.requestRightList(cardId,currpage,tabIndex); 
    store.dispatch(addList(response.result,currpage));
    store.dispatch(changeLoading(false));
};
原文地址:https://www.cnblogs.com/xiaozhumaopao/p/10567738.html