redux基礎react-thunk的基本使用

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中可以監測

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章