react中实现异步请求的方法一,react-thunk

写在前面:

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