• react dva发送请求详解(转)


    1,在jsx页面派发任务,可以在componentWillMount的生命周期内,
    使用this.props.dispatch方法派发,需要先引用connect模块,不引用会报错

    import { connect } from 'dva';

    在类中操作:

    class 类名 extends React.Component {
      constructor(props){
        super(props)
      }
      componentWillMount() {
        this.props.dispatch({
          type: '自定义的namespace/effects中的方法名',
          payload: {//可以不填
            参数名:参数值
          },
        })
      }
      render() {
      //查看网络请求传递出来的内容
      console.log(this.props.data)
      //this.props.data为mapStateToProps中的data
        return (
          <div></div>
        )
      }
    }
    
    const mapStateToProps = (state) => {  //见名知意,把state转换为props
      //可以打印state看看数据结构,然后放到data里
      return {
        data:state.data
      };
    };
    export default connect(mapStateToProps)(类名)

    2,services文件夹下创建单独的发送网络请求js,比如service.js

    import request from '../utils/request';
    
    export function models中要调用的方法名 (参数) {
      return request(`接口地址?${参数}`) //get方法请求
        /*
       return request(`接口地址`,{
        method: 'post',
        headers: {
          'Content-Type': 'application/json; charset=utf-8'
        },
        body: JSON.stringify({
          参数名:参数
        })
      })
      */
      
    }

    3,models文件夹下创建操作数据的js,比如data.js

    import * as 自定义名 from '../services/service';
    
    export default {
      namespace: '第一步中的namespace',
    
      state: {
        data: ''   //reducers中接收数据
      },
    
      subscriptions: {
        setup({ dispatch, history }) {  // eslint-disable-line
        },
      },
    
      effects: {
    
        *供组件调用的方法名({ payload: { 参数 }}, { call, put }) {
    
          const result = yield call(自定义名.service中的方法名, 参数);//如果使用  {参数}  ,则是一个对象
    
          //把请求的数据保存起来
          //数据更新会带动页面重新渲染
          yield put({
            type: 'save',  //reducers中的方法名
            payload:{
              data: result.data  //网络返回的要保留的数据
            }
          })
        }
      },
    
      reducers: {
         save(state, { payload: { data } }) {
           return {
             ...state, 
              data: data  //第一个data是state的,第二个data是payload的
          };
         },
      },
    }

    使用data.js可以在主js中:

    import dva from 'dva';
    const app = dva();
    app.model(require('./models/data'));

    第二步中引用的request.js⬇️,不需要改动

    import fetch from 'dva/fetch';
    
    function parseJSON(response) {
      return response.json();
    }
    
    function checkStatus(response) {
      if (response.status >= 200 && response.status < 300) {
        return response;
      }
    
      const error = new Error(response.statusText);
      error.response = response;
      throw error;
    }
    
    /**
     * Requests a URL, returning a promise.
     *
     * @param  {string} url       The URL we want to request
     * @param  {object} [options] The options we want to pass to "fetch"
     * @return {object}           An object containing either "data" or "err"
     */
    export default function request(url, options) {
      return fetch(url, options)
        .then(checkStatus)
        .then(parseJSON)
        .then(data => ({ data }))
        .catch(err => ({ err }));
    }

    参考:https://www.jianshu.com/p/6482f4785929

    https://www.jianshu.com/p/5aa95d62339c

    https://blog.csdn.net/hzxOnlineOk/article/details/102930679

  • 相关阅读:
    leetcode231 2的幂 leetcode342 4的幂 leetcode326 3的幂
    leetcode300. Longest Increasing Subsequence 最长递增子序列 、674. Longest Continuous Increasing Subsequence
    leetcode64. Minimum Path Sum
    leetcode 20 括号匹配
    算法题待做
    leetcode 121. Best Time to Buy and Sell Stock 、122.Best Time to Buy and Sell Stock II 、309. Best Time to Buy and Sell Stock with Cooldown 、714. Best Time to Buy and Sell Stock with Transaction Fee
    rand7生成rand10,rand1生成rand6,rand2生成rand5(包含了rand2生成rand3)
    依图
    leetcode 1.Two Sum 、167. Two Sum II
    从分类,排序,top-k多个方面对推荐算法稳定性的评价
  • 原文地址:https://www.cnblogs.com/dongxiaolei/p/13997185.html
Copyright © 2020-2023  润新知