Redux详细入门教程


在这里插入图片描述

目录
  • 你可能不需要 Redux
  • 简介
  • 安装
  • 原则
  • 核心API
    • 1. Store
    • 2. State
    • 3. Action
    • 4. Action Creator
    • 5. store.dispatch()
    • 6. Reducer
    • 7. store.subscribe()
  • 工作流程
  • 完整实例


你可能不需要 Redux

首先明确一点,Redux 是一个有用的架构,但不是非用不可。事实上,大多数情况,你可以不用它,只用 React 就够了。

鲁迅(∩_∩) 曾经说过: "如果你不知道是否需要 Redux,那就是不需要它。"
Redux 的创造者 Dan Abramov 又补充了一句:"只有遇到 React 实在解决不了的问题,你才需要 Redux 。"

简单说,如果你的UI层非常简单,没有很多互动,Redux 就是不必要的,用了反而增加复杂性。

不需要使用 Redux:

  • 用户的使用方式非常简单
  • 用户之间没有协作
  • 不需要与服务器大量交互,也没有使用 WebSocket
  • 视图层(View)只从单一来源获取数据

需要使用 Redux:

  • 组件需要共享数据(或者叫做状态state)的时候
  • 某个状态需要在任何地方都可以被随时访问的时候
  • 某个组件需要改变另一个组件的状态的时候
  • 语言切换、暗黑模式切换、用户登录全局数据共享 ...

简介

Redux 是 js 应用的可预测状态的容器。 可以理解为全局数据状态管理工具(状态管理机),用来做组件通信等。

Redux 的设计思想很简单,就两句话:

  1. Web 应用是一个状态机,视图与状态是一一对应的。

  2. 所有的状态,保存在一个对象里面。

在这里插入图片描述

Redux架构原理:

  1. 剥离组件数据(state)
  2. 数据统一存放在store中
  3. 组件订阅store获得数据
  4. store推送数据更新

类似与vue的状态管理vuex

一句话总结:Redux统一保存了数据,在隔离了数据与UI的同时,负责处理数据的绑定。


安装

yarn add redux

npm install redux --save


原则

  1. store是唯一的 (整个应用只能有一个 store)
  2. 只有store能改变自己的内容 (store里的数据不是reducer更新的)
  3. reducer必须是纯函数 (只要是同样的输入,必定得到同样的输出)

核心API

在这里插入图片描述

1. Store

Store 就是保存全局数据的地方,你可以把它看成一个容器(带有推送功能的数据仓库)。整个应用只能有一个 Store

Redux 提供createStore这个函数,用来生成 Store。

import { createStore } from 'redux';
const store = createStore(fn);

2. State

Store对象包含所有数据。如果想得到某个时点的数据,就要对 Store 生成快照。这种时点的数据集合,就叫做 State。

当前时刻的 State,可以通过store.getState()拿到。

import { createStore } from 'redux';
const store = createStore(fn);

const state = store.getState();

Redux 规定, 一个 State 对应一个 View。只要 State 相同,View 就相同。你知道 State,就知道 View 是什么样,反之亦然。

3. Action

State 的变化,会导致 View 的变化。但是,用户接触不到 State,只能接触到 View。所以,State 的变化必须是 View 导致的。

Action 就是 View 发出的通知,表示 State 应该要发生变化了。

Action 是一个对象。其中的type属性是必须的,表示 Action 的名称。其他属性可以自由设置,社区有一个规范可以参考。

const action = {
    type: 'change_input',
    value: 'Learn Redux',
};

上面代码中,Action 的名称是change_input,它携带的信息是字符串Learn Redux

可以这样理解,Action 描述当前发生的事情。改变 State 的唯一办法,就是使用 Action。它会运送数据到 Store。

4. Action Creator

过多的Action在组件中,会显得代码过于臃肿,不利于阅读和维护
可以新建一个actionCreator.js文件,用来统一管理action

src/store/actionCreator.js

// action的统一管理

export const changeInputAction = value => ({
    type: 'change_input',
    value,
});

export const addItemAction = () => ({
    type: 'add_item',
});

export const delItemAction = index => ({
    type: 'del_item',
    index,
});

export const initListAction = list => ({
    type: 'init_list',
    list,
});

每个函数都用来返回一个action,这个函数就叫 Action Creator

5. store.dispatch()

store.dispatch()是 View 发出 Action 的唯一方法

import { createStore } from 'redux';
const store = createStore(fn);

const action = {
    type: 'change_input',
    value: 'Learn Redux',
};

store.dispatch(action);

结合 Action Creator,这段代码可以改写如下:

import { createStore } from 'redux';
import { changeInputAction } from 'src/store/actionCreator.js'

const store = createStore(fn);

store.dispatch(changeInputAction('Learn Redux'));

6. Reducer

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

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

可以新建一个reducer.js文件,用来统一管理

src/store/reducer.js

// 初始状态,作为 State 的默认值
const defaultState = {
    value: ''
};

const reducer = (state = defaultState, action) => {
    let newState = JSON.parse(JSON.stringify(state)); // 深拷贝,不能直接修改state里的数据
    if (action.type === 'change_input') {
        newState.value = action.value;
    }
    if (action.type === 'add_item') {
        newState.list.push(newState.value);
        newState.value = '';
    }
    if (action.type === 'del_item') {
        newState.list.splice(action.index, 1);
    }
    if (action.type === 'init_list') {
        newState.list = action.list;
    }
    return newState;
};

export default reducer;

reducer函数收到名为change_inputadd_itemdel_iteminit_list的 Action 后,就返回一个新的 State(newState),作为结果抛出。

在生成 Store 的时候,将 reducer 传入createStore()。以后每当store.dispatch发送过来一个新的 Action,就会自动调用 reducer,得到新的 State

import { createStore } from 'redux';
import reducer from 'src/store/reducer.js';

const store = createStore(reducer);

7. store.subscribe()

Store 允许使用store.subscribe()方法设置监听函数一旦 State 发生变化,就自动执行这个函数

import { Component} from 'react';
import store from './store/index';

class List extends Component {
    constructor(props) {
        super(props);
        store.subscribe(this.storeChange.bind(this)); // store发生改变时,自动触发storeChange方法
    }
    render() {
        return (
			// ....
        );
    }
    storeChange() {
        // store发生改变时,将自动触发
        let newState = store.getState();  // 得到当前state状态,包含所有store属性
        this.setState(newState);  // 重新渲染 View
    }
}

export default List;

store.subscribe方法返回一个函数,调用这个函数就可以解除监听

let unsubscribe = store.subscribe(() =>
  console.log(store.getState())
);

unsubscribe(); // 解除监听

工作流程

在这里插入图片描述

1. 用户发出 Action

const action = {
    type: 'change_input',
    value: 'Learn Redux',
};

store.dispatch(action);

2. Store 自动调用 Reducer,并且传入两个参数:当前 State 和收到的 Action。 Reducer 会返回新的 State(newState)

const reducer = (state, action) => {
    let newState = JSON.parse(JSON.stringify(state)); // 深拷贝,不能直接修改state里的数据
    if (action.type === 'change_input') {
        newState.value = action.value;
    }
    return newState;
};

export default reducer;

3. State 一旦有变化,Store 就会调用监听函数

store.subscribe(this.storeChange.bind(this)); // store发生改变时,自动触发storeChange方法

4.storeChange()可以通过store.getState()得到当前状态。如果使用的是 React,这时可以触发重新渲染 View

storeChange() {
    // store发生改变时,将自动触发
    let newState = store.getState();  // 得到当前state状态,包含所有store属性
    this.setState(newState);  // 重新渲染 View
}

完整实例

src/store/index.js

import { createStore } from 'redux';
import reducer from './reducer';

const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__());

export default store;

src/list.js

import store from './store/index';
import { changeInputAction } from './store/actionCreator';

class List extends Component {
    constructor(props) {
        super(props);
        this.state = store.getState();  // 获取store中所有的数据
        store.subscribe(this.storeChange.bind(this)); // store发生改变时,自动触发
    }
    render() {
        return (
            
); } storeChange() { this.setState(store.getState()); } change(e) { const action = changeInputAction(e.target.value); store.dispatch(action); // 派发action给store } } export default List;

src/store/actionCreator.js

export const changeInputAction = value => ({
    type: 'change_input',
    value,
});

src/store/reducer.js

const defaultState = {
    value: ''
};

const reducer = (state = defaultState, action) => {
    console.log(state, action);
    let newState = JSON.parse(JSON.stringify(state)); // 深拷贝,不能直接修改state里的数据
    if (action.type === 'change_input') {
        newState.value = action.value;
    }
    return newState;
};

export default reducer;