redux 中间件用法

redux 中的 store 仅支持同步数据流。使用 thunk 等中间件可以帮助在 redux 中实现异步操作。

redux-thunk 使用流程

  • 下载 redux-thunk

    npm install redux-thunk -S
    
  • store 中引入 redux-thunk 中间件,并挂载 redux-thunk 实例

    import {createStore,applyMiddleware} from 'redux'
    import reducer from './reducer'
    // redux-thunk 中间价 是store支持异步派发
    import thunk from 'redux-thunk'
    const store = createStore(reducer,applyMiddleware(thunk));
    export default store
    
  • 组件中异步派发

    // 使用 中间件 可以在 action 中发送ajax请求等。
    const getGoodsList = () => {
        return (dispatch) => {
            fetch('http://demo.com/api/demoDemoItem')
                .then(response => response.json())
                .then(res => {
                  dispatch({
                      type: 'GET_GOODS_LIST',
                      data: res
                  })
                })
        }
    }
    export {
        getGoodsList
    }
    

参考文章:

posted @ 2020-12-09 21:06  公瑾当年  阅读(199)  评论(0编辑  收藏  举报