码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-03-09 23:39:17      阅读:707      评论:0      收藏:0      [点我收藏+]

标签:export   module   extend   ret   set   family   操作   color   patch   

写在前面:

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;

 

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

标签:export   module   extend   ret   set   family   操作   color   patch   

原文地址:https://www.cnblogs.com/PrayLs/p/10503615.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!