16.使用Redux-thunk中间键实现ajax数据请求19-05-28

到Github中搜redux-thunk,点开start最多的中间件的目录,打开,有使用步骤,找到Installation先安装

npm install redux-thunk

yarn add redux-thunk

在store的index中引入applyMiddleware方法,使我们可以使用中间件方法。
import { createStore , applyMiddleware} from 'redux';

再引入rudux模块儿
import thunk from 'redux-thunk';
在createStore中添加applyMiddleware(thunk),即创建store的时候会使用thunk中间件。

以下是同时使用redux-devtools的代码改写


redux-devtools-extension
高级商店设置中
1.2 Advanced store setup
复制代码

const composeEnhancers =
  typeof window === 'object' &&
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?   
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
      // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
    }) : compose;

const enhancer = composeEnhancers(
  applyMiddleware(...middleware),
  // other store enhancers if any
);

以便使用中间件thunk,同时引用redux_devtools

+  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()

代码改写如下

import { createStore , applyMiddleware,compose} from 'redux';
import reducer from './reducer';
import thunk from 'redux-thunk';

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;

4.当使用了redux_thunk以后,action可以是一个函数了

export const getTodoList = () => {  
//使用了redux_thunk这里可以return一个函数了
return () => {
//函数里就可以做异步的操作
axios.get('/list.json').then((res)=>{
//此处使用Charles实现本地数据,(https://www.jianshu.com/p/b73ca383a31b)
      const data = res.data;
     // console.log(data);
     // const action = initListAction(data);
     // dispatch(action);
   }
}

5.调用getTodoList这个函数
到TodoList.js中引入getTodoList函数

import {getInputChangeAction,getAddItemAction,getDeleteItemAction,getTodoList} from './store/actionCreators'

创建一个action
const action = getTodoList();//打印action,这里的action返回的是一个函数

componentDidMount() {
    const action = getTodoList();
    store.dispatch(action);//直接通过dispatch方法把action发给store,此时action里的函数会自动执行
    console.log(action);
  }

6.创建action改变store里的数据

export const initListAction = (data)=>({
  type:INIT_LIST_ACTION,
  data
});
export const getTodoList = () => {
  return (dispatch) => {//getTodoList 是函数可以接收到store的dispatch方法。
    axios.get('/list.json').then((res)=>{
      const data = res.data;
      console.log(data);
      const action = initListAction(data);
      dispatch(action);//调用dispatch方法把action发给store
    })
  }
}

附加

什么是redux中间件


371559099163_.pic.jpg

中间件是action和store之间的 ,对dispatch方法的封装或升级

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容