React 03 Redux状态管理

0. 什么是Redux?

一套状态管理工具。

Redux is a predictable state container for JavaScript apps.

Redux是JavaScript应用程序的可预测状态容器。

1. 你不一定需要Redux

阮一峰老师在他的Redux系列教程里面对于你是否需要Redux有过非常精辟的论述。

如果你不知道是否需要 Redux,那就是不需要它。

只有遇到 React 实在解决不了的问题,你才需要 Redux 。

这个是阮一峰老师的系列教程,一共有两篇,感兴趣的小伙伴可以去看一下,讲的非常好,不过是基于ReactJs讲的,我们这篇文章会基于React+Typescript来讲解他的用法。

Redux 入门教程(一):基本用法

Redux 入门教程(二):中间件与异步操作

2. Store, Action, Reducer

2.1 Store

就是保存数据的地方,你可以把它看成一个容器。整个应用只能有一个 Store。

每一个Component都将自己的状态数据存放到Store中,当Store中的状态发生改变,会下发给每一个Connect到Store的Component,调用Component的render方法。

按照Redux的官方文档,Store中的State是只读的,如果要修改State的状态,只能通过Reducer生成新的State实例。

2.2 Action

每一个Component只能通过发送Action到Store来修改Store中的State。Action是一个数据结构,可以参考这个规范来定义Action的结构。

对于Action的定义,一般会按照如下方式定义:

export interface Action {
    // Action的Type一般是一个字符串常量,Reducer会使用这个Type来修改状态
    type: string; 
    // Payload的类型与Component的State的类型对应
    payload: number;
}
复制代码
  • Action Creator

一般会创建一个纯函数来创建一个View相对应的Action。

export function onLike(count: number): LikeAction {
    return {
        type: FETCH_LIKE_COUNT,
        payload: count
    };
}
复制代码
  • 发送Action

一般会通过调用store.dispatch(action),将action发送给Store,store将action分发给对应的reducer来处理。不过在本篇的Demo中,我们使用了typescript推荐的connect方式,所以dispatch的方式略有不同,后续会通过Demo详细介绍。

const mapDispatchToProps = (dispatch: Dispatch<AnyAction>) => ({
    onLike: (count: number) => dispatch(onLike(count))
});

export const LikeWrapper = connect(mapStateToProps, mapDispatchToProps)(Like);
复制代码

2.3 Reducer

在上一节中,提到了Reducer,这一节来详细介绍Reducer。

Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer。

Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。

Reducer会接受两个参数,一个是state,另一个是action。下面的例子展示了如何编写一个Reducer函数。

export function likeReducer(state = initState, action: any): LikeState {
    let result = initState;
    // 前面提到,Reducer会根据action.type返回各种新的state。
    // 按照Redux的官方文档,state是只读的,不能修改,只能生成新的state。
    switch (action.type) {
        case FETCH_LIKE_COUNT:
            result = {
                ...state,
                count: action.payload
            };
            break;
        default:
            result = state;
            break;
    }
    return result;
}
复制代码

3. Redux工作流程

下面这个图展示了从Component生成一个Action开始,如何更新State,之后如何根据new-state更新Component的UI。

ComponentStoreReducerscreate action1dispatch(action1)send action1 to specific reducerGenerate new State by action1.typeupdate(new-state)new-statemerge props with new-state, call render()ComponentStoreReducers

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享