React-Redux-thunk

当前保存异步数据存在的问题

异步数据既然要保存到 Redux 中, 所以获取异步数据也应该是 Redux 的一部分,所以获取异步数据的代码应该放到 Redux 中, 而不是放到组件生命周期方法中。

在 Redux 中获取网络数据

  • 使用 redux-thunk 中间件

redux-thunk 作用

默认情况下 dispatch 只能接收一个对象, 使用 redux-thunk 可以让 dispatch 除了可以接收一个对象以外, 还可以接收一个函数, 是的通过 dispatch 派发一个函数的时候能够去执行这个函数, 而不是执行 reducer 函数。

使用 redux-thunk

  • 安装 redux-thunk
npm install redux-thunk
  • 在创建 store 时应用 redux-thunk 中间件

修改 store.js:

import {createStore, applyMiddleware} from 'redux'
import thunkMiddleware from 'redux-thunk'

import reducer from './reducer';

// 创建store之前,通过applyMiddleware方法,告诉Redux需要应用哪些中间件
const storeEnhancer = applyMiddleware(thunkMiddleware);
// 利用store来保存状态(state)
const store = createStore(reducer, storeEnhancer);

export default store;
  • 在 action 中获取网络数据
export const getUserInfo = (dispatch, getState) => {
    fetch('http://127.0.0.1:7001/info')
        .then((response) => {
            return response.json();
        })
        .then((data) => {
            console.log('在action中获取到的网络数据', data);
        })
        .catch((error) => {
            console.log(error);
        });
}
  • 在组件中派发 action
import React from 'react';
import {getUserInfo} from "../store/action";
import connect from "../connect/connect";

class About extends React.PureComponent {
    componentDidMount() {
        this.props.changeInfo();
    }

    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() {
            dispatch(getUserInfo);
        }
    }
};
export default connect(mapStateToProps, mapDispatchToProps)(About);
  • 最终在 action 当中保存数据,在派发的方法当中会自动的将 dispatch 传入到方法的参数列表上,然后可以在通过 dispatch 在此派发任务进行保存数据,更改 action.js
export const getUserInfo = (dispatch, getState) => {
    fetch('http://127.0.0.1:7001/info')
        .then((response) => {
            return response.json();
        })
        .then((data) => {
            dispatch(changeAction(data));
        })
        .catch((error) => {
            console.log(error);
        });
}

注意点

默认情况下 dispatch 方法只能接收一个对象, 如果想让 dispatch 方法除了可以接收一个对象以外, 还可以接收一个方法, 那么我们可以使用 redux-thunk 中间件, redux-thunk 中间件的作用,可以让 dispatch 方法可以接收一个函数, 可以让我们在通过 dispatch 派发任务的时候去执行我们传入的方法。

总结

  • 使用 redux-thunk 之前的流程
                 --------------------
        ------>  | Component 异步请求 |  -----
       |         --------------------       |
       |                                    ↓
-------------       -------------       -------------
|   Store   | <---- |  Reducer  | <---- |  Action   |
-------------       -------------       -------------
  • 使用 redux-thunk 之后
                    -------------
        --------->  | Component |  ---------------------------------
       |            -------------                                   |
       |                                                            ↓
-------------       -------------       -------------       -------------
|   Store   | <---- |  Reducer  | <---- |  异步请求   | <---- |  Action   |
-------------       -------------       -------------       -------------

官方文档地址

posted @ 2022-06-02 20:36  BNTang  阅读(38)  评论(0编辑  收藏  举报