1.github上搜索redux-thunk,他是redux的中间件,作用主要是让dispatch(action) 方法可以传入一个函数,而不一定是action对象
准确的来说是传入的函数的返回值 可以是一个方法或者函数 不一定是action对象 只是这个函数能够接收到dispatch 对象return的时候在执行一下 dispatch(aciton) 这个时候就可以是一个对象了
相当于在dispatch外面装饰了一个方法 这个方法处理了逻辑之后 在执行dispatch()
这个函数可以return 一个函数 该函数可以接收一个dispatch方法 然后可以实现请求后台数据之后调用dispatch方法改变store值
2.关于如何使用和配置可以参考GitHub上面的文档介绍 ,上面都是英文文档
注意点
renderItem={(item, index) => (<List.Item onClick={() => { props.deleteItem(index) }}
renderItem={(item, index) => (<List.Item onClick={(index) => { props.deleteItem(index) }} //onClick中的index参数不是外部函数的index参数而是事件的event对象,有e.target 可以打印一下
注意变量的作用域问题 外部的index参数 是作用于 整个方法,所以可以直接传入到onClick方法中
同时使用thunk 中间件 和redux-devtools-extensions 工具
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk'
import reducer from '../reducer/';
//通过官方文档的使用方式
const composeEnhancers =
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
}) : compose;
const enhancer = composeEnhancers(
//applyMiddleware(...middleware),
applyMiddleware(thunk),
);
//通过applyMiddleware 使用redux 的中间件thunk
const store = createStore(reducer, enhancer);
// const store = createStore(reducer, applyMiddleware(thunk));
export default store
actionCreator //把请求抽出来放到action 中 逻辑清洗 便于自动化测试
export const getToDoList = () => {
return (dispatch) => {
axios.get('/apis/getMv').then((res) => {
console.log('res', res)
dispatch(initItem(res.data));
}).catch(() => {
})
}
}
//如果使用调用方法
componentDidMount = () => {
// axios.get('/apis/getMv').then((res) => {
// console.log('res', res)
// store.dispatch(initItem(res.data));
// }).catch(() => {
// })
store.dispatch(getToDoList())// 传入的可以是一个函数 该函数返回值可以不是Acton对像 而是一个函数
}