redux-thunk(中间件)学习(二)
1、react请求数据
- 使用axois 安装 yarn add axios
- 在项目public 新建 list.json文件
- 一般请求数据的方法放在componentDidMount钩子函数中进行
componentDidMount () {
axios.get('./list.json').then((res) => {
const data = res.data.list;
store.dispatch(initList(data))
}).catch((e) => {
console.log(e);
})
};2、引用redux-thunk中间件来优化请求(action->store中间的处理,其实就是对dispatch的处理)
action只能传对象,因为请求是方法,所以想在actionCreator.js中使用方法,需要引用redux-thunk,这样做的好处,避免组件的臃肿,统一管理请求- 安装redux-thunk yarn add redux-thunk
- 在githup上看redux-think的使用 链接描述
import { createStore ,applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';
const store = createStore(
reducer,
applyMiddleware(thunk)
);
export default store;- 在actionCreator.js
export const getListData = () =>{
return (dispatch) => {
axios.get('/list.json').then((res) => {
const data = res.data.list;
dispatch(initList(data))
}).catch((e) => {
console.log(e);
})
}
}- 组件中使用
componentDidMount () {
store.dispatch(getListData()) ;
};组件中运用store.dispatch的方法把action创建的方法转给store,(如果不用redux-thunk插件, store接受的action只能是对象,用了redux-thunk后就可以接受方法了)store会自动执行action函数,函数中会执行对应的对象action从而实现了上述功能。3、方便在chrome浏览器中观察到store的数据,需要安装react devtools插件,安装插件需要翻墙
安装好插件后,项目里面需要安装redux-devtools-extension
步骤
- yarn add redux-devtools-extension
- 参考githup上的使用链接描述
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),
// other store enhancers if any
);
const store = createStore(
reducer,
enhancer
);
export default store;