美文网首页
21.异步action

21.异步action

作者: __疯子__ | 来源:发表于2020-06-01 11:15 被阅读0次

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

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>

相关文章

  • 21.异步action

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

  • 高级

    异步 Action 通过 redux-thunk ,在 action 中 dispatch action ,可以是...

  • Vuex之Action

    Action为mutation服务,因为Action可以包含任意异步操作。 分发Action Actions 支持...

  • nuxt开发部署指南

    1. vuex 不要在Mutation中做异步操作,需要做异步操作用action action调用通过dispat...

  • Vuex4.x(四)action的各种使用方式

    action 的用法 由于mutation不支持异步操作,所以vuex又提供了action,这个可以支持异步,在有...

  • Redux 的中间件和异步操作

    一、同步和异步 首先讲一下在redux之中,Action的同步和异步的概念。 异步:Action发出之后,过一段时...

  • 10-redux-thunk使用

    Time: 20200129 异步Action Creator需要用到同步Action Creator. 完整代码...

  • Spark 异步Action

    What if we want to execute 2 actions concurrently on diff...

  • redux 异步action

    redux 异步action yarn add redux-thunk 参考 Redux Thunk api请求demo

  • React的异步处理

    React的异步处理 通常情况下,action只是一个对象,不能包含异步操作,这导致了很多创建action的逻辑只...

网友评论

      本文标题:21.异步action

      本文链接:https://www.haomeiwen.com/subject/rerjzhtx.html