Redux——redux-thunk:使得action可以是一个函数

前言:对于复杂的action,如ajax异步请求后修改store,建议使用 redux-thunk 来简化 action


1、下载 redux-thunk 和配置 redux-thunk

  • 下载 redux-thunk
npm i redux-thunk
  • 基本配置,在 ./store/index.js 中配置
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';

const store = createStore(rootReducer, applyMiddleware(thunk));
  • 在使用 redux-devtools 插件同时使用 redux-thunk,在 ./store/index.js 中配置
import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import reducer from './reducer'

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose

// 这里传入中间件
const enhancer = composeEnhancers( applyMiddleware(thunk) )

const store = createStore( reducer, enhancer )

export default store

2、使用 redux-thunk

  1. 这时候action就可以是一个函数了,不用重新在外面定义一个拿到数据后在dispatch,更有整体性
  • 这里模拟 ajax 异步请求后改变 store
componentDidMount(){
	// 参数 dispatch 是向 store 发型 action
    const action = (dispatch) => {
        // 假设这里ajax异步请求到了数据 list
        const list = [1,2,3]
        const action = {
            type: 'init_list',
            list
        }
        dispatch(action)
    }
    store.dispatch(action) //如果传入函数,会自动执行这个函数
}

  1. 在 actionCreators 中使用 redux-thunk
export const initList = () => {
	// 参数 dispatch 是向 store 发型 action
    return (dispatch) => {
        // 假设这里ajax异步请求到了数据 list
        const list = [1,2,3]
        const action = {
            type: 'init_list',
            list
        }
        dispatch(action)
    }
}
  • Test.js
componentDidMount(){
   const action = initList()
   store.dispatch(action) //如果传入函数,会自动执行这个函数
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值