非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
三大原则
Redux 可以用三个基本原则来描述:
单一数据源
这使得创建通用应用变得简单,因为服务器端的状态可以直接序列化并注入客户端,无需额外编码。单一状态树还便于调试或检查应用,同时支持在开发过程中持久化应用状态以加速开发周期。某些传统上难以实现的功能(如撤销/重做)在状态集中存储后变得异常简单。
console.log(store.getState())
/* Prints
{
visibilityFilter: 'SHOW_ALL',
todos: [
{
text: 'Consider using Redux',
completed: true,
},
{
text: 'Keep all state in a single tree',
completed: false
}
]
}
*/
状态只读
改变状态的唯一方式是触发action,即描述发生事件的对象。
这确保了视图和网络回调永远不会直接修改状态,而是表达状态转换意图。由于所有变更都集中处理且严格按序执行,无需担心隐晦的竞态条件。action 作为纯对象可被记录、序列化、存储,并在后续回放用于调试或测试。
store.dispatch({
type: 'COMPLETE_TODO',
index: 1
})
store.dispatch({
type: 'SET_VISIBILITY_FILTER',
filter: 'SHOW_COMPLETED'
})
使用纯函数修改
通过编写纯reducer来定义 action 如何转换状态树。
Reducer 是纯函数,接收旧状态和 action,返回新状态。请始终返回新状态对象而非修改旧状态。应用初期可使用单个 reducer,随着应用增长可拆分为管理特定状态分支的小型 reducer。由于 reducer 本质是函数,您可以控制执行顺序、传递额外数据,甚至创建可复用的通用 reducer(如分页逻辑)。
function visibilityFilter(state = 'SHOW_ALL', action) {
switch (action.type) {
case 'SET_VISIBILITY_FILTER':
return action.filter
default:
return state
}
}
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
{
text: action.text,
completed: false
}
]
case 'COMPLETE_TODO':
return state.map((todo, index) => {
if (index === action.index) {
return Object.assign({}, todo, {
completed: true
})
}
return todo
})
default:
return state
}
}
import { combineReducers, createStore } from 'redux'
const reducer = combineReducers({ visibilityFilter, todos })
const store = createStore(reducer)
就是这样!现在你已掌握 Redux 的核心精髓。