21.异步action

注意:本篇文章是根据上一篇文章进行修改的,如果需要源码,请去上一篇文章中进行复制! 源码-传送门

react-redux基本流程

  • 创建reducers
  • 合并reducers
  • createStore
  • Provider store={store}
  • @connect(mapStateToProps,{...actionCreators})(YourComponent)
  • actionsCreates
  • 修改reducers

异步Action参考文档

  1. 安装依赖

cnpm i -D redux-thunk

2.引用applyMiddleware (src/store.js)

import { createStore,applyMiddleware} from 'redux'

3.引用redux-thunk(src/store.js)

import thunk from 'redux-thunk'

4.修改导出配置src/store.js

export default createStore(
  rootReducer,
  applyMiddleware(thunk)//如果是多个直接在后面添加参数就可以
)

5.添加减的函数为异步操作src/actions/cart.js

//异步action,使用redux-thunk之后,就可以在actionCreator里return一个方法,这个方法的参数dispatch
export const decrementAsync=id=>dispatch=>{
  setTimeout(()=>{
      dispatch({
          type:actionType.CART_ITEM_DECREMENT,
          payload:{
              id
          }
      })
  })
};
//上面方法等同于下面这个方法
// export const decrementAsync=(id)=>{
//     return dispatch=>{
//         setTimeout(()=>{
//             dispatch({
//                 type:actionType.CART_ITEM_DECREMENT,
//                 payload:{
//                     id
//                 }
//             })
//         },200)
//     }
// }

6.引入decrementAsync (src/components/CartList/index.js)

import { increment,decrement,decrementAsync} from '../../actions/cart'

7.修改导出配置src/components/CartList/index.js

export default connect(mapStateToProps,{decrement,increment,decrementAsync})(CartList)

8.添加按钮并且添加点击事件

//在button 减上面添加
<button onClick={()=>{this.props.decrementAsync(item.id)}}>异步</button>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。