基本方法
1.获取数据
在组件中通过请求接口获取数据,并通过dispatch方法分发action
componentDidMount(){axios.get('http://localhost:5000/getList').then(res=>{const {data}=resconst action = getListAction(data)store.dispatch(action)})}
2.在actionType文件中创建新的action type
export const GET_LIST = "getList";
3.在actionCreators文件中创建新的action
export const getListAction = (data) => ({type: GET_LIST,data,});
4.在reducer文件中处理业务逻辑
if (action.type === GET_LIST) {let newState = JSON.parse(JSON.stringify(state));newState.list=action.data.data.Listreturn newState;}
使用Redux-thunk中间件
1.配置redux-thunk
首先,在store中的index文件中 引入redux-thunk ,然后 再在redux引入中加入applyMiddleware和compose 其中compose用来兼容redux-devtools
配置之前👇
import {createStore} from 'redux';import reducer from '../reducer';const store = createStore(reducer,window.__REDUX_DEVTOOLS_EXTENSION__&&window.__REDUX_DEVTOOLS_EXTENSION__)export default store
配置之后👇
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__({}):composeconst enhanser =composeEnhancers(applyMiddleware(thunk))const store = createStore(reducer,enhanser)export default store
如果不使用redux-devtools则可如下配置👇
import {createStore,applyMiddleware} from 'redux';import reducer from './reducer';import thunk from 'redux-thunk';const store = createStore(reducer,applyMiddleware(thunk))export default store
2.在actionCreators文件中创建新的action
在这个异步action中 我们reture的并不再是一个对象,而是一个函数,函数中传入一个参数dispatch,在函数中请求接口并使用参数的dispatch来分发之前用来处理逻辑的同步action(getListAction),参数中的dispatch可以直接分发到store中
export const getListAction = (data) => ({type: GET_LIST,data,});export const getTodoList = () => {return (dispatch) => {axios.get("http://localhost:5000/getList").then((res) => {const { data } = res;const action = getListAction(data);dispatch(action);});};};
3.在组件中分发异步cation
componentDidMount(){const action = getTodoList()store.dispatch(action);}
