react中實現異步請求的方法一,react-thunk

寫在前面:react

react中,dispatch是同步執行reducers生成新狀態的,對於頁面的操做沒有問題;可是若是點擊事件是請求了某個結果,須要等待結果響應後再更新視圖呢?應該如何處理?這裏就用到了異步請求。react-thunk是解決這一問題的一個方法之一。ajax

 

一、先看設置跨域的代碼,文件名必須爲setupProxy.jsjson

 

const proxy = require("http-proxy-middleware");
module.exports = (app)=>{
    app.use("/api",proxy({
        //須要跨域的目標域名
        target:"http://m.maoyan.com",
        //是否開啓代理
        changeOrigin:true,
        //路徑重寫
        pathRewrite:{
            "^/api":""
        }
    }))
}

 

二、store中設置中間件redux

 

//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;

 

三、actionCreator中進行請求api

 

//引入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));
        })
    }
}

 

四、在組件中執行請求數據的函數跨域

 

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;
相關文章
相關標籤/搜索