Fork me on GitHub

Redux笔记

image

文章概述

本篇文章记录Redux的笔记。

redux

Redux的设计思想

  1. Web 应用是一个状态机,视图与状态是一一对应的。
  2. 所有的状态,保存在一个对象里面。

基本API

操作或View交互会产生一个Action,Action运送数据到Store,Store接受Action后产生一个state,View改变。

Store(数据存储)

概念

Store就是保存数据的地方,Store对象包含所有数据,整个应用只能有一个Store;

createStore创建Store
  • Redux提供createStore这个函数,用来生成Store,createStore函数接受另一个函数作为参数,返回新生成的Store对象。
1
2
import { createStore } from 'redux';
const store = createStore(fn);
  • createStore方法还可以接受第二个参数,表示 State 的最初状态。这通常是服务器给出的。
1
2
3
//window.STATE_FROM_SERVER就是整个应用的状态初始值
//注意,如果提供了这个参数,它会覆盖 Reducer 函数的默认初始值。
let store = createStore(todoApp, window.STATE_FROM_SERVER)
createStore的实现

createStore方法的一个简单实现,可以了解一下 Store 是怎么生成的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const createStore = (reducer) => {
let state;
let listeners = [];

const getState = () => state;

const dispatch = (action) => {
state = reducer(state, action);
listeners.forEach(listener => listener());
};

const subscribe = (listener) => {
listeners.push(listener);
return () => {
listeners = listeners.filter(l => l !== listener);
}
};

dispatch({});

return { getState, dispatch, subscribe };
};
Store的三个方法
  • store.getState()
  • store.dispatch()
  • store.subscribe()
1
2
import { createStore } from 'redux';
let { subscribe, dispatch, getState } = createStore(reducer);
获取状态
1
store.getState()
store.dispatch(发Action)

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

  • 发出一个Action:
1
2
3
4
5
6
7
import { createStore } from 'redux';
const store = createStore(fn);

store.dispatch({
type: 'ADD_TODO',
payload: 'Learn Redux'
});
  • 结合Action Creator:
1
store.dispatch(addTodo('Learn Redux'));
监听函数
概念

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

1
store.subscribe()

使用

只要把 View 的更新函数(对于 React 项目,就是组件的render方法或setState方法)放入listen,就会实现 View 的自动渲染。

1
2
3
4
import { createStore } from 'redux';
const store = createStore(reducer);

store.subscribe(listener);

解除监听

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

1
2
3
4
5
let unsubscribe = store.subscribe(() =>
console.log(store.getState())
);

unsubscribe();

State(数据)
概念
  • 如果想得到某个时点的数据,就要对Store生成快照。这种时点的数据集合,就叫做State。
  • 当前时刻的State,可以通过store.getState()拿到。
1
2
3
4
import { createStore } from 'redux';
const store = createStore(fn);

const state = store.getState();
  • Redux规定,一个State对应一个View。只要State相同,View就相同。你知道State,就知道View 是什么样,反之亦然。
Action(改变state操作)
概念

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

要点

Action是一个对象。其中的type属性是必须的,表示Action的名称。其他属性可以自由设置;

1
2
3
4
5
//Action 的名称是ADD_TODO,它携带的信息是字符串Learn Redux
const action = {
type: 'ADD_TODO',
payload: 'Learn Redux'
};
Action Creator(生成Action)

View 要发送多少种消息,就会有多少种Action。如果都手写,会很麻烦。可以定义一个函数来生成 Action,这个函数就叫 Action Creator。

1
2
3
4
5
6
7
8
9
10
11
const ADD_TODO = '添加 TODO';

//addTodo函数就是一个 Action Creator。
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}

const action = addTodo('Learn Redux');

Reducer(获取State)

概念

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

要点

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

1
2
3
4
const reducer = function (state, action) {
// ...
return new_state;
};
实际应用

实际应用中,Reducer 函数不用像上面这样手动调用,store.dispatch方法会触发 Reducer 的自动执行。为此,Store 需要知道 Reducer 函数,做法就是在生成 Store 的时候,将 Reducer 传入createStore方法。

1
2
import { createStore } from 'redux';
const store = createStore(reducer);
生成State
纯函数reducer
  • 不得改写参数
  • 不能调用系统 I/O 的API
  • 不能调用Date.now()或者Math.random()等不纯的方法,因为每次会得到不一样的结果
生成不变的新State

Reducer 是纯函数,就可以保证同样的State,必定得到同样的 View。但也正因为这一点,Reducer 函数里面不能改变 State,必须返回一个全新的对象,请参考下面的写法。最好把 State 对象设成只读。你没法改变它,要得到新的 State,唯一办法就是生成一个新对象。这样的好处是,任何时候,与某个View对应的State总是一个不变的对象

1
2
3
4
5
6
7
8
9
10
11
// State 是一个对象
function reducer(state, action) {
return Object.assign({}, state, { thingToChange });
// 或者
return { ...state, ...newState };
}

// State 是一个数组
function reducer(state, action) {
return [...state, newItem];
}

Reducer拆分

Reducer函数负责生成State。由于整个应用只有一个State对象,包含所有数据,对于大型应用来说,这个State 必然十分庞大,导致Reducer函数也十分庞大。

Reducer生成State示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const chatReducer = (state = defaultState, action = {}) => {
const { type, payload } = action;
switch (type) {
case ADD_CHAT:
return Object.assign({}, state, {
chatLog: state.chatLog.concat(payload)
});
case CHANGE_STATUS:
return Object.assign({}, state, {
statusMessage: payload
});
case CHANGE_USERNAME:
return Object.assign({}, state, {
userName: payload
});
default: return state;
}
};

上面代码中,三种Action分别改变State的三个属性:

  • ADD_CHAT:chatLog属性
  • CHANGE_STATUS:statusMessage属性
  • CHANGE_USERNAME:userName属性

我们可以把Reducer函数拆分。不同的函数负责处理不同属性,最终把它们合并成一个大的Reducer即可。如下:

1
2
3
4
5
6
7
8
//Reducer 函数被拆成了三个小函数,每一个负责生成对应的属性:
const chatReducer = (state = defaultState, action = {}) => {
return {
chatLog: chatLog(state.chatLog, action),
statusMessage: statusMessage(state.statusMessage, action),
userName: userName(state.userName, action)
}
};
拆分合并工具

Redux 提供了一个combineReducers方法,用于Reducer的拆分。只要定义各个子 Reducer函数,然后用这个方法,将它们合成一个大的 Reducer。

1
2
3
4
5
6
7
8
9
10
//combineReducers方法将三个子 Reducer 合并成一个大的函数
import { combineReducers } from 'redux';

const chatReducer = combineReducers({
chatLog,
statusMessage,
userName
})

export default todoApp;
要点
  • State的属性名必须与子Reducer同名,如果不同名,就要采用下面的写法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const reducer = combineReducers({
a: doSomethingWithA,
b: processB,
c: c
})

// 等同于
function reducer(state = {}, action) {
return {
a: doSomethingWithA(state.a, action),
b: processB(state.b, action),
c: c(state.c, action)
}
}

Redux工作流程

相关概念梳理
  • Reducer:纯函数,只承担计算 State 的功能,不合适承担其他功能,也承担不了,因为理论上,纯函数不能进行读写操作。
  • View:与 State 一一对应,可以看作 State 的视觉层,也不合适承担其他功能。
  • Action:存放数据的对象,即消息的载体,只能被别人操作,自己不能进行任何操作。
工作流程
  1. 用户发出Action;
1
store.dispatch(action);
  1. Store自动调用Reducer,并且传入两个参数:当前State和收到的Action,Reducer会返回新的State;
1
let nextState = todoApp(previousState, action);
  1. Store就会调用监听函数,监听State变化;
1
2
// 设置监听函数
store.subscribe(listener);
  1. 监听函数可以通过store.getState()得到当前状态。如果使用的是React,这时可以触发重新渲染 View。
1
2
3
4
function listerner() {
let newState = store.getState();
component.setState(newState);
}
示例:计数器

简单的计数器Counter,唯一的作用就是把参数value的值,显示在网页上,并为Counter添加递增和递减的Action:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const Counter = ({ value, onIncrement, onDecrement }) => (
<div>
<h1>{value}</h1>
<button onClick={onIncrement}>+</button>
<button onClick={onDecrement}>-</button>
</div>
);

const reducer = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT': return state + 1;
case 'DECREMENT': return state - 1;
default: return state;
}
};

const store = createStore(reducer);

const render = () => {
ReactDOM.render(
<Counter
value={store.getState()}
onIncrement={() => store.dispatch({type: 'INCREMENT'})}
onDecrement={() => store.dispatch({type: 'DECREMENT'})}
/>,
document.getElementById('root')
);
};

render();
store.subscribe(render);

Reducer异步处理

概念
  • Action发出以后,Reducer立即算出State,这叫做同步;
  • Action发出以后,过一段时间再执行Reducer,这就是异步。
中间件

我们可以store.dispatch这一步添加中间件来增加其功能;

之前我们知道createStore可以接受两个参数,reducer和一个初始状态,此处介绍,他可以接受第三个参数applyMiddleware,来应用中间件,初始状态参数可以省略。

applyMiddleware

applyMiddleware作用是将所有中间件组成一个数组,依次执行(log类型的中间件要放在数组最后);

异步操作的基本思路

同步操作只要发出一种Action即可,异步操作的差别是它要发出三种Action:

  1. 操作发起时的 Action;
  2. 操作成功时的 Action;
  3. 操作失败时的 Action;

【注意】
此处三种action,但是实际操作中值会发起两次Action对象,即:操作时发起Action,操作结束发起一次Action.

redux-thunk中间件

store.dispatch方法正常情况下,参数只能是对象,不能是函数.这里我们借助中间件redux-thunk来改造store.dispatch,让他可以接收函数作为参数,这样我们可以利用接收的函数作为参数,在操作结束后再发起Action,从而实现异步的目的。

改造写法

使用redux-thunk中间件,改造store.dispatch,使得后者可以接受函数作为参数。

1
2
3
4
5
6
7
8
9
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducers';

// Note: this API requires redux@>=3.1.0
const store = createStore(
reducer,
applyMiddleware(thunk)
);

redux-promise中间件

既然Action Creator可以返回函数,当然也可以返回其他值。另一种异步操作的解决方案,就是用redux-promise中间件让Action Creator返回一个Promise对象。

redux-promise中间件使得store.dispatch方法可以接受Promise对象作为参数.

引入中间件
1
2
3
4
5
6
7
8
import { createStore, applyMiddleware } from 'redux';
import promiseMiddleware from 'redux-promise';
import reducer from './reducers';

const store = createStore(
reducer,
applyMiddleware(promiseMiddleware)
);
生成Action的两种方式

使用redux-promise中间件时,Action Creator有两种写法:
方法1. 返回的Action是一个Promise对象:

1
2
3
4
5
6
7
8
9
const fetchPosts = 
(dispatch, postTitle) => new Promise(function (resolve, reject) {
dispatch(requestPosts(postTitle));
return fetch(`/some/API/${postTitle}.json`)
.then(response => {
type: 'FETCH_POSTS',
payload: response.json()
});
});

方法2. 返回的Action的属性是一个Promise对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//这需要从redux-actions模块引入createAction方法
import { createAction } from 'redux-actions';

class AsyncApp extends Component {
componentDidMount() {
const { dispatch, selectedPost } = this.props
// 发出同步 Action
dispatch(requestPosts(selectedPost));
// 发出异步 Action
dispatch(createAction(
'FETCH_POSTS',
fetch(`/some/API/${postTitle}.json`)
.then(response => response.json())
));
}

【注解】dispatch方法发出的是异步Action,只有等到操作结束,这个 Action 才会实际发出。注意,createAction的第二个参数必须是一个 Promise 对象。

react-redux

Redux的作者封装的一个React专用的Redux库React-Redux,来进行state管理;

安装

1
yarn add react-redux -S

对组件分类

React-Redux将所有组件分成两大类:

  1. UI 组件(presentational component),UI组件负责UI的呈现,容器组件负责管理数据和逻辑;
  2. 容器组件(container component),负责管理数据和业务逻辑。
UI组件

因为不含有状态,UI 组件又称为”纯组件”,即它纯函数一样,纯粹由参数决定它的值。

UI组件有以下几个特征:

  • 只负责UI的呈现,不带有任何业务逻辑;
  • 没有状态(即不使用this.state这个变量);
  • 所有数据都由参数(this.props)提供;
  • 不使用任何Redux的API;
容器组件
  • 负责管理数据和业务逻辑,不负责UI的呈现;
  • 带有内部状态;
  • 使用Redux的API;

connect()

React-Redux 提供connect方法,用于从UI组件生成容器组件。connect的意思,就是将这两种组件连起来;

connect的用法:可接收两个方法参数,分别负责输入输出逻辑的方法,根据UI组件生成容器组件;

1
2
3
4
5
6
7
8
9

import { connect } from 'react-redux'
//VisibleTodoList就是由 React-Redux 通过connect方法自动生成的容器组件;
const VisibleTodoList = connect(
//负责输入逻辑:即将state映射到UI组件的参数(props);
mapStateToProps,
//负责输出逻辑: 即将用户对UI组件的操作映射成Action。
mapDispatchToProps
)(TodoList) //TodoList是UI组件
mapStateToProps()

mapStateToProps是一个函数,作为connect函数的第一个参数,作用是建立一个从UI组件外部的state对象输入到UI组件的props对象的映射关系。

【函数结构】

  • mapStateToProps的第一个参数总是state对象;
  • 可以使用第二个参数,代表容器组件的props对象,使用组件的props作为参数后,如果容器组件的参数发生变化,也会引发UI组件重新渲染。

【工作逻辑】

  • mapStateToProps函数会订阅Store,每当state更新的时候,就会自动执行,重新计算UI组件的参数,从而触发UI组件的重新渲染。
  • connect方法可以省略mapStateToProps参数,那样的话,UI组件就不会订阅Store,就是说 Store 的更新不会引起UI组件的更新。

【示例代码】:

注释:mapStateToProps是一个函数,它接受state作为参数,返回一个对象。这个对象有一个todos属性,代表UI组件的同名参数,后面的getVisibleTodos也是一个函数,可以从state算出todos的值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const mapStateToProps = (state) => {
return {
todos: getVisibleTodos(state.todos, state.visibilityFilter)
}
}
const getVisibleTodos = (todos, filter) => {
switch (filter) {
case 'SHOW_ALL':
return todos
case 'SHOW_COMPLETED':
return todos.filter(t => t.completed)
case 'SHOW_ACTIVE':
return todos.filter(t => !t.completed)
default:
throw new Error('Unknown filter: ' + filter)
}
}

mapDispatchToProps()

mapDispatchToProps是connect函数的第二个参数,用来建立UI组件的参数到store.dispatch方法的映射。它定义了哪些用户的操作应该当作Action,传给Store,它可以是一个函数,也可以是一个对象。

【mapDispatchToProps是一个函数】

  • mapDispatchToProps是一个函数会得到dispatch和ownProps(UI组件的props对象)两个参数,返回一个对象,该对象的每个键值对都是一个映射,定义了UI 组件的参数怎样发出Action。
1
2
3
4
5
6
7
8
9
10
11
12
13
const mapDispatchToProps = (
dispatch,
ownProps
) => {
return {
onClick: () => {
dispatch({
type: 'SET_VISIBILITY_FILTER',
filter: ownProps.filter
});
}
};
}

【mapDispatchToProps是一个对象】
如果mapDispatchToProps是一个对象,它的每个键名也是对应UI组件的同名参数,键值应该是一个函数,会被当作Action creator,返回的Action会由Redux自动发出。

1
2
3
4
5
6
const mapDispatchToProps = {
onClick: (filter) => {
type: 'SET_VISIBILITY_FILTER',
filter: filter
};
}

Provider组件

React-Redux提供Provider组件,可以让容器组件拿到state:

  1. 根组件使用Provider:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    import { Provider } from 'react-redux'
    import { createStore } from 'redux'
    import todoApp from './reducers'
    import App from './components/App'

    let store = createStore(todoApp);

    render(
    //Provider在根组件外面包了一层,这样一来,App的所有子组件就默认都可以拿到state了。
    <Provider store={store}>
    <App />
    </Provider>,
    document.getElementById('root')
    )
  2. 子组件就可以从context拿到store:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class VisibleTodoList extends Component {
componentDidMount() {
const { store } = this.context;
this.unsubscribe = store.subscribe(() =>
this.forceUpdate()
);
}

render() {
const props = this.props;
const { store } = this.context;
const state = store.getState();
// ...
}
}

VisibleTodoList.contextTypes = {
store: React.PropTypes.object
}

react-redux工作流程示例

以下用react-redux来实现一个计数器示例的步骤:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import { Provider, connect } from 'react-redux'

//【1. 定义一个计数器UI组件】
class Counter extends Component {
render() {
const { value, onIncreaseClick } = this.props
return (
<div>
<span>{value}</span>
<button onClick={onIncreaseClick}>Increase</button>
</div>
)
}
}

Counter.propTypes = {
value: PropTypes.number.isRequired,
onIncreaseClick: PropTypes.func.isRequired
}

//【2. 定义输入内容到UI组件,和UI组件输出Action】
// Map Redux state to component props
function mapStateToProps(state) {
return {
value: state.count
}
}

//Action Creator
const increaseAction = { type: 'increase' }

// Map Redux actions to component props
function mapDispatchToProps(dispatch) {
return {
onIncreaseClick: () => dispatch(increaseAction)
}
}

//【3. 使用connect方法生成容器组件】
// Connected Component
const App = connect(
mapStateToProps,
mapDispatchToProps
)(Counter)

//【4. Reducer接收action生成新state】
// Reducer
function counter(state = { count: 0 }, action) {
const count = state.count
switch (action.type) {
case 'increase':
return { count: count + 1 }
default:
return state
}
}

//【5. 生成store对象】
const store = createStore(counter)

//【6. 根组件包裹Provider】
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)

provider结合react-router

使用React-Router的项目,与其他项目没有不同之处,也是使用Provider在Router外面包一层,毕竟Provider的唯一功能就是传入store对象。

1
2
3
4
5
6
7
const Root = ({ store }) => (
<Provider store={store}>
<Router>
<Route path="/" component={App} />
</Router>
</Provider>
);

坚持原创技术分享,您的支持将鼓励我继续创作!