1、在store中配置使用redux-thunk
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(thunk),
)
const store = createStore(reducer, enhancer);
export default store
2、在action中實現請求數據
export function getHttpData() {
// 獲取http請求的數據
return (dispatch) => {
axios.get('https://api.apiopen.top/getJoke?page=1&count=2&type=video')
.then(res => {
console.log(res)
dispatch(httpData(res)) // 派送獲取到的值到store
})
.catch(err => {
console.log(err)
})
}
}
3、在需要調用的地方使用派遣action
componentDidMount() {
store.dispatch(getHttpData())
}
4、reducer.js中可以監測