react基礎使用redux-thunk實現action中請求異步數據

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中可以返回函數,獲取請求數據

import axios from 'axios'

export function getHttpData() {
  // 獲取網絡異步數據
  return (dispath) => {
    axios.get('https://api.apiopen.top/getJoke?page=1&count=2&type=video')
    .then(res => {
      console.log(res)
    })
    .catch(err => {
      console.log(err)
    })
  }
}

3、在需要調用的地方派送相關action

componentDidMount() {
    // 在組件掛載在頁面上的時候
    console.log("執行了沒");
    store.dispatch(getHttpData())
  }

 

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