06/19 14:17
相关文章
三大原则
Redux 可以用这三个基本原则来描述:
单一数据源
整个应用的 state 被储存在一棵 object tree 中,并且这个 object tree 只存在于唯一一个 store 中。
State 是只读的
唯一改变 state 的方法就是触发 action,action 是一个用于描述已发生事件的普通对象。
使用纯函数来执行修改
为了描述 action 如何改变 state tree ,需要编写 reducers。刚开始可以只有一个 reducer,随着应用变大,可以把它拆成多个小的 reducers,分别独立地操作 state tree 的不同部分。
概念简介
Store
Store 就是保存数据的地方,你可以把它看成一个容器。整个应用只能有一个 Store。
State
某时刻的数据状态。
Redux 规定, 一个 State 对应一个 View。只要 State 相同,View 就相同。State 的变化,会导致 View 的变化。
Action
Action 就是 View 发出的通知,表示 State 应该要发生变化了。
Action 是一个对象。其中的 type
属性是必须的,表示 Action 的名称。其他属性可以自由设置。
const action = {
type: 'ADD_TODO',
payload: 'Learn Redux'
};
Action Creator
定义一个函数来生成 Action,这个函数就叫 Action Creator。
function addTodo(text) {
// return 的是一个 Action
return {
type: ADD_TODO,
text
}
}
Reducer
Reducer 是一个纯函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。
根据 Action 的 type 返回不同的 State:
const defaultState = 0;
const reducer = (state = defaultState, action) => {
switch (action.type) {
case 'ADD':
return state + action.payload;
default:
return state;
}
};
const state = reducer(1, {
type: 'ADD',
payload: 2
});
思维导图
工作流程