zoukankan      html  css  js  c++  java
  • 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;
  • 相关阅读:
    Jmeter简单使用
    Linux命令补充
    数据加密
    问题 Can't load AMD 64-bit .dll on a IA 32-bit platform
    需要知道的东西很多还要知道的牢固
    Sqlyog问题
    精神苦难和快乐
    了解一个名词——GTD
    超强记忆力提升九大心法-10连锁记忆法
    Array数组结构底层实现复习
  • 原文地址:https://www.cnblogs.com/PrayLs/p/10503615.html
Copyright © 2011-2022 走看看