Redux 学习笔记

Posted by CodingWithAlice on January 18, 2025

Redux 学习笔记

一、定义

状态容器,提供可预测的、集中式的状态管理方式,适用于大型复杂项目 - 只有2kb,插件生态强大

核心逻辑:Redux Toolkit,包括了常见工具 - 配置store(对象树)、创建reducer并编写immutable更新逻辑等

二、基础

1、应用的「整体全局状态」以「对象树」的方式存放于「单个 store」

2、唯一改变「状态树」的方法是创建 action - 一个描述发生了什么的对象

3、将 action dispatch 给 store

拆解:reducer

函数签名: (preState, action) => newState - 从旧的state和action计算出新 state 值

用途:要指定状态树「怎么响应 action 」来进行更新,可以使用 reducer

重点:不是直接改变 state 对象,而是在 state 发生变化时「返回一个新对象」

import { createStore } from 'redux'; // 引入创建 redux store 的模块
function reducer( state = { count: 0 }, action ) { // 1、自定义一个 reducer
    if( action.type ) { 
        return { count: state.count++ } 
    } 
}
// store 有三个 API - subscribe, dispatch, getState
let store = createStore(reducer); // 2、创建一个 store
store.dispatch({ type: true });// 3、改变内部状态的唯一方法是 dispatch 一个 action
store.subscribe(() => console.log(store.getState()));// 4、可以使用 subscribe() 来更新 UI 以响应 state 的更改
拆解2:action

action 其实就是一个 JS 对象 - redux 的核心就是「如何根据 action 对象来更新 state」

强制使用 action 可以统一管理应用中 state 的改变