寫在前面:
在react中,dispatch是同步執行reducers生成新狀態的,對於頁面的操作沒有問題;但是如果點擊事件是請求了某個結果,需要等待結果響應后再更新視圖呢?應該如何處理?這里就用到了異步請求。react-thunk是解決這一問題的一個方法之一。
1、先看設置跨域的代碼,文件名必須為setupProxy.js
const proxy = require("http-proxy-middleware"); module.exports = (app)=>{ app.use("/api",proxy({ //需要跨域的目標域名 target:"http://m.maoyan.com", //是否開啟代理 changeOrigin:true, //路徑重寫 pathRewrite:{ "^/api":"" } })) }
2、在store中設置中間件
//applyMiddleware使用中間件 import {createStore,applyMiddleware} from "redux"; //引入redux-thunk import thunk from "redux-thunk"; import reducer from "./reducer"; //使用react-thunk const store = createStore(reducer,applyMiddleware(thunk)); export default store;
3、在actionCreator中進行請求
//引入fetch,為了和瀏覽器中自帶的fetch區分重命名fetchpro import {fetch as fetchpro} from "whatwg-fetch"; //現在的action是一個函數 export const MovieAction = ()=>{ let action = (val)=>({ type:"GET_MOVIE", value:val }) return (dispatch,getState)=>{ fetchpro("/api/ajax/movieOnInfoList?token=") .then(res=>res.json()) .then((data)=>{ dispatch(action(data)); }) } }
4、在組件中執行請求數據的函數
import React, { Component } from 'react'; import store from "./store"; import {MovieAction} from "./action/actionCreator"; class App extends Component { render() { return ( <div className="App"> </div> ); } handleGetMovie(){ store.dispatch(MovieAction()) } //在掛載后這個生命周期函數中調用 componentDidMount(){ this.handleGetMovie(); } } export default App;