React-Redux-处理网络数据

在看怎么获取之前首先博主这里使用了 Egg 搭建了一个后台,下载,然后将 Egg 项目启动起来不介绍如何启动不会的自行去学习 Egg,然后启动了之后就可以进行下一步操作了,然后更改我们的前端 React 代码进行发送网络请求拿到数据这里采用 fetch 进行请求。

  • 更改 About.js 如下
import React from 'react';

class About extends React.PureComponent {
    componentDidMount() {
        fetch('http://localhost:7001/info')
            .then(resp => {
                return resp.json();
            })
            .then(data => {
                console.log(data);
            })
            .catch(error => {
                console.log(error);
            });
    }

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

export default About;

image-20220529221509312

从如上图中发现数据已经拿到了,然后呐,就开始更改我们的 reducer.js 定义一个状态

// 定义一个状态
let initialState = {
    count: 666,
    info: {}
};
  • 更改 constants.js 添加一个常量
export const CHANGE_INFO = 'CHANGE_INFO';
  • 更改 action.js 添加一个 action
import {
    ...
    CHANGE_INFO
} from './constants';

...

export const changeAction = (info) => {
    return {type: CHANGE_INFO, info: info};
};
  • 在 reducer 当中处理任务
import {
    ...
    CHANGE_INFO
} from './constants';

...

// 利用reducer将store和action串联起来
function reducer(state = initialState, action) {
    switch (action.type) {
        case ADD_COUNT:
            return {...state, count: state.count + action.num};
        case SUB_COUNT:
            return {...state, count: state.count - action.num};
        case CHANGE_INFO:
            return {...state, info: action.info};
        default:
            return state;
    }
}

export default reducer;
  • 然后在 About.js 当中在获取到网络数据的时候调用派发的方法传递一个数据,然后对应的 action 会保存到对应的状态当中,这样就实现了将网络的数据保存在 Redux 当中了
import React from 'react';
import {changeAction} from "../store/action";
import connect from "../connect/connect";

class About extends React.PureComponent {
    componentDidMount() {
        fetch('http://localhost:7001/info')
            .then(resp => {
                return resp.json();
            })
            .then(data => {
                this.props.changeInfo(data);
            })
            .catch(error => {
                console.log(error);
            });
    }

    render() {
        return (
            <div>
                <p>{this.props.info.name}</p>
                <p>{this.props.info.age}</p>
            </div>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        info: state.info
    }
};
const mapDispatchToProps = (dispatch) => {
    return {
        changeInfo(info) {
            dispatch(changeAction(info));
        }
    }
};
export default connect(mapStateToProps, mapDispatchToProps)(About);

image-20220529222655272

posted @ 2022-05-29 23:24  BNTang  阅读(65)  评论(0编辑  收藏  举报