React-Redux-thunk

简介: React-Redux-thunk

前言


React-Redux-Thunk是一个用于处理Redux异步操作的中间件,它扩展了Redux的能力,使您能够更轻松地处理异步操作,如网络请求或定时任务。


通常,Redux的reducers是同步的,但在现实应用中,需要在数据获取或其他异步操作完成后才能更新状态。这就是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   |
-------------       -------------       -------------       -------------



官方文档地址




最后

本期结束咱们下次再见👋~

🌊 关注我不迷路,如果本篇文章对你有所帮助,或者你有什么疑问,欢迎在评论区留言,我一般看到都会回复的。大家点赞支持一下哟~ 💗

相关文章
|
9月前
|
存储 JavaScript 前端开发
【React】redux和React-redux
redux和React-redux
65 0
|
7月前
|
JavaScript 前端开发 中间件
React(六) —— redux
React(六) —— redux
|
7月前
|
Web App开发 JavaScript 前端开发
React | Redux的使用详解(二)
React | Redux的使用详解(二)
|
7月前
|
存储 缓存 JavaScript
React | Redux的使用详解(一)
React | Redux的使用详解(一)
|
8月前
|
JavaScript 前端开发 中间件
说说你对Redux的理解?和react-redux有什么区别?
说说你对Redux的理解?和react-redux有什么区别?
|
10月前
|
存储 JavaScript 中间件
React-thunk
React-thunk
38 0
|
10月前
|
存储 JavaScript 前端开发
React-Redux[上]
React-Redux[上]
60 0
|
10月前
|
存储 JavaScript 前端开发
React-Redux[中]
React-Redux[中]
50 0
|
10月前
React-Redux[下]
React-Redux[下]
30 0
|
JavaScript 前端开发
React 中 Redux 详解
React 中 Redux 详解