React-thunk

React-Thunk在redux中获取异步数据
  1. 当前保存异步数据存在的问题
    以前获取数据都是在组件的生命周期方法中进行获取并且在组件中存储,但是数据需要储存到redux中。异步数据既然要保存到Redux中, 所以获取异步数据也应该是Redux的一部分,所以获取异步数据的代码应该放到Redux中, 而不是放到组件生命周期方法中
  2. 如何在Redux中获取网络数据?
    使用redux-thunk中间件
  3. redux-thunk作用?
    默认情况下dispatch只能接收一个对象,
    使用redux-thunk可以让dispatch除了可以接收一个对象以外, 还可以接收一个函数,是通过dispatch派发一个函数的时候能够去执行这个函数, 而不是执行reducer函数
  4. redux-thunk如何使用?
  • 安装redux-thunk
    npm install redux-thunk
  • 在创建store时应用redux-thunk中间件
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
//在创建redux之前告诉redux需要应用thunkMiddleware的中间件,其返回结果是一个对象
const storeEnhancer =  applyMiddleware(thunkMiddleware);

// 利用store来保存状态(state)
const store = createStore(reducer, storeEnhancer);
  • 在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);
            dispatch(changeAction(data));
        })
        .catch((error)=>{
            console.log(error);
        })
}
  • 在组件中派发action
import React from 'react';
import { connect } from 'react-redux'
import {addAction, subAction, getUserInfo} from '../store/action';
class About extends React.PureComponent{
    componentDidMount() {
        this.props.changeInfo();
    }

    render(){
        return (
            <div>
                <p>{this.props.count}</p>
                <button onClick={()=>{this.props.decrement()}}>递减</button>
                <p>{this.props.info.name}</p>
                <p>{this.props.info.age}</p>
            </div>
        )
    }
}
// 在mapStateToProps方法中告诉React-Redux, 需要将store中保存的哪些数据映射到当前组件的props上
const mapStateToProps = (state)=>{
    return {
        count: state.count,
        info: state.info
    }
};
const mapDispatchToProps = (dispatch) =>{
    return {
        decrement(){
            dispatch(subAction(1));
        },
        changeInfo(info){
            dispatch(getUserInfo);
        }
    }
};
export default connect(mapStateToProps, mapDispatchToProps)(About);

官方文档地址: https://www.redux.org.cn/docs/advanced/AsyncActions.html

此时就实现了在redux里面获取数据和存储数据。

react-thunk执行流程
使用redux-thunk之前:
                 --------------------
        ------>  | Component 异步请求 |  -----
       |         --------------------       |
       |                                    ↓
-------------       -------------       -------------
|   Store   | <---- |  Reducer  | <---- |  Action   |
-------------       -------------       -------------

使用redux-thunk之后:
                    -------------
        --------->  | Component |  ---------------------------------
       |            -------------                                   |
       |                                                            ↓
-------------       -------------       -------------       -------------
|   Store   | <---- |  Reducer  | <---- |  异步请求   | <---- |  Action   |
-------------       -------------       -------------       -------------
React-thunk实现原理

在redux-thunk中:

  • 如果通过dispatch派发的任务是一个对象, 那么就立即执行reducer
  • 如果通过dispatch派发的任务是一个函数, 那么就执行这个函数
function thunkDispatch(action) {
    console.log('执行reducer之前做的事情');
    if(typeof action === 'function'){
        action(store.dispatch, store.getState);
    }else{
        store.dispatch(action);
    }
}

优化:将官方的dispatch改为我们自己的dispatch

function thunkDispatch(store) {
    const storeDispath = store.dispatch;
    const storeGetState = store.getState;
    function myDispatch(action) {
        if(typeof action === 'function'){
            action(storeDispath, storeGetState);
        }else{
            storeDispath(action);
        }
    }
    // 将官方的dispatch函数修改为我们自定义的dispatch函数
    store.dispatch = myDispatch;
}
thunkDispatch(store);
// 调用的实际是我们自定义的dispatch函数
store.dispatch(addAction);
store.dispatch(getUserInfo);
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 前言 刚来公司的时候,对react项目中的thunk中间件的作用一直不太了解,最近有时间决定好好研究一下。鉴于本人...
    world_7735阅读 3,676评论 0 5
  • asynchronous action creator 做数据取回,至少发送3个不同的actions: an ac...
    JamesSawyer阅读 1,759评论 0 0
  • 一. 概述 React与Vue是我们熟悉的两大前端主流框架,来自官方的解释,Vue是一套用于构建用户界面的渐进式框...
    QiShare阅读 1,804评论 0 2
  • React框架学习 React的起源和发展 起初facebook在建设instagram(图片分享)的时候嘞,因为...
    hcySam阅读 811评论 0 1
  • 第1章 课程导学 学习前提要有一些js、es6、webpack、npm等基础知识 第2章 React初探 2-1 ...
    读书的鱼阅读 3,157评论 0 26

友情链接更多精彩内容