1.设计思想
(1)Web 应用是一个状态机,视图与状态是一一对应的。
(2)所有的状态,保存在一个对象里面。
Store 就是保存数据的地方,你可以把它看成一个容器。整个应用只能有一个 Store。
Redux 提供
createStore
这个函数,用来生成 Store。
import { createStore } from 'redux';
const store = createStore(fn);
//createStore
函数接受另一个函数作为参数,返回新生成的 Store 对象
Store
对象包含所有数据。如果想得到某个时点的数据,就要对 Store 生成快照。这种时点的数据集合,就叫做 State。当前时刻的 State,可以通过store.getState()
拿到。
import { createStore } from 'redux';
const store = createStore(fn);const state = store.getState();
State 的变化,会导致 View 的变化。但是,用户接触不到 State,只能接触到 View。所以,State 的变化必须是 View 导致的。Action 就是 View 发出的通知,表示 State 应该要发生变化了。
Action 是一个对象。其中的type
属性是必须的,表示 Action 的名称。
const action = {
type: 'ADD_TODO',
payload: 'Learn Redux'
};
const ADD_TODO = '添加 TODO';
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}const action = addTodo('Learn Redux');
store.dispatch()
是 View 发出 Action 的唯一方法。import { createStore } from 'redux';
const store = createStore(fn);store.dispatch({
type: 'ADD_TODO',
payload: 'Learn Redux'
});
Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer。
Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。
const reducer = function (state, action) {
// ...
return new_state;
};