【前端知识】React 基础巩固(三十四)——组件中的异步操作及优化

React 基础巩固(三十四)------组件中的异步操作及优化

一、待优化的异步请求流程

  • 通过组件的生命周期来完成网络请求,网络请求的异步代码直接放在组件中
javascript 复制代码
import React, { PureComponent } from "react";
import { connect } from "react-redux";
import {
  changeBannerAction,
  changeRecommendAction,
} from "../store/actionCreators";
import axios from "axios";

export class category extends PureComponent {
  componentDidMount() {
    axios.get("http://123.207.32.32:8000/home/multidata").then((res) => {
      console.log(res.data);
      const banners = res.data.data.banner.list;
      const recommends = res.data.data.recommend.list;
      console.log(banners, recommends);
      this.props.changeBanners(banners);
      this.props.changeRecommends(recommends);
    });
  }

  render() {
    return <div>category</div>;
  }
}

const mapDispatchToProps = (dispatch) => ({
  changeBanners(banners) {
    dispatch(changeBannerAction(banners));
  },
  changeRecommends(recommends) {
    dispatch(changeRecommendAction(recommends));
  },
});

export default connect(null, mapDispatchToProps)(category);

二、利用Redux优化异步网络请求

  • 通过redux来管理异步网络请求

  • 在store中引入中间件redux-thunk

    javascript 复制代码
    import { createStore, applyMiddleware } from "redux";
    import reducer from "./reducer";
    import thunk from "redux-thunk";
    
    // 正常情况下,store.dispatch 只能派发对象
    // 想要派发函数,需要增强,使用 "redux-thunk"
    
    const store = createStore(reducer, applyMiddleware(thunk));
    
    export default store;
  • 构建fetchHomeMultidataAction,将原本在组件中的异步请求代码放入到actionCreators.js中

    javascript 复制代码
    import * as actionTypes from "./constants";
    import axios from "axios";
    
    export const addNumberAction = (num) => ({
      type: actionTypes.ADD_NUMBER,
      num,
    });
    
    export const subNumberAction = (num) => ({
      type: actionTypes.SUB_NUMBER,
      num,
    });
    
    export const changeBannerAction = (banners) => ({
      type: actionTypes.CHANGE_BANNERS,
      banners,
    });
    
    export const changeRecommendAction = (recommends) => ({
      type: actionTypes.CHANGE_RECOMMENDS,
      recommends,
    });
    
    export const fetchHomeMultidataAction = () => {
      return (dispatch, getState) => {
        // 异步操作
        axios.get("http://123.207.32.32:8000/home/multidata").then((res) => {
          const banners = res.data.data.banner.list;
          const recommends = res.data.data.recommend.list;
          dispatch(changeBannerAction(banners))
          dispatch(changeRecommendAction(recommends))
        });
      }
    };
  • 改写原来的category.jsx,派发异步请求的dispatch

    javascript 复制代码
    import React, { PureComponent } from "react";
    import { connect } from "react-redux";
    import { fetchHomeMultidataAction } from "../store/actionCreators";
    // import axios from "axios";
    
    export class category extends PureComponent {
      componentDidMount() {
        // axios.get("http://123.207.32.32:8000/home/multidata").then((res) => {
        //   console.log(res.data);
        //   const banners = res.data.data.banner.list;
        //   const recommends = res.data.data.recommend.list;
        //   console.log(banners, recommends);
        //   this.props.changeBanners(banners);
        //   this.props.changeRecommends(recommends);
        // });
    
        this.props.fetchHomeMultidata();
      }
    
      render() {
        const { banners, recommends } = this.props;
        return (
          <div>
            category
            <div className="banner">
              <h2>轮播图:</h2>
              <ul>
                {banners.map((item, index) => {
                  return <li key={index}>{item.title}</li>;
                })}
              </ul>
            </div>
            <div className="recommend">
              <h2>推荐数据:</h2>
              <ul>
                {recommends.map((item, index) => {
                  return <li key={index}>{item.title}</li>;
                })}
              </ul>
            </div>
          </div>
        );
      }
    }
    
    const mapStateToProps = (state) => ({
      counter: state.counter,
      banners: state.banners,
      recommends: state.recommends,
    });
    
    const mapDispatchToProps = (dispatch) => ({
      //   changeBanners(banners) {
      //     dispatch(changeBannerAction(banners));
      //   },
      //   changeRecommends(recommends) {
      //     dispatch(changeRecommendAction(recommends));
      //   },
      fetchHomeMultidata(recommends) {
        dispatch(fetchHomeMultidataAction(recommends));
      },
    });
    
    export default connect(mapStateToProps, mapDispatchToProps)(category);
  • 查看运行结果

相关推荐
Martin -Tang2 分钟前
vite和webpack的区别
前端·webpack·node.js·vite
迷途小码农零零发3 分钟前
解锁微前端的优秀库
前端
王解1 小时前
webpack loader全解析,从入门到精通(10)
前端·webpack·node.js
老码沉思录1 小时前
写给初学者的React Native 全栈开发实战班
javascript·react native·react.js
老码沉思录1 小时前
React Native 全栈开发实战班 - 第四部分:用户界面进阶之动画效果实现
react native·react.js·ui
我不当帕鲁谁当帕鲁1 小时前
arcgis for js实现FeatureLayer图层弹窗展示所有field字段
前端·javascript·arcgis
那一抹阳光多灿烂1 小时前
工程化实战内功修炼测试题
前端·javascript
放逐者-保持本心,方可放逐2 小时前
微信小程序=》基础=》常见问题=》性能总结
前端·微信小程序·小程序·前端框架
毋若成4 小时前
前端三大组件之CSS,三大选择器,游戏网页仿写
前端·css
红中马喽4 小时前
JS学习日记(webAPI—DOM)
开发语言·前端·javascript·笔记·vscode·学习