Redux
Redux 是 JavaScript 状态容器,提供可预测化的状态管理。一般与React一同使用。
Redux使用普通对象存储 state,但是state不能随意被修改。
通过action(普通对象)传递数据变化的载荷,即发生变化的条件(type)和新数据:
{
type: '', // 固定写法
newState,
...
}
通过reducer具体描述数据如何变化。
三大原则
- 单一数据源:整个应用的 state 被储存在一棵 object tree 中,并且这个 object tree 只存在于唯一一个 store中。
- State只读:唯一改变state的方法就是触发action。
- 使用纯函数来执行修改:执行修改操作的reducer函数必须是纯函数,即不能改变入参(state),不能执行有副作用的操作。
基础
Action
action就是一个对象:
{
type: '', // 固定写法,指定将要执行哪些操作
newState, // 即将参与state更新的数据
...
}
一般使用Action创建函数返回action对象:
function actionCreator(data) {
return {
type: 'someString',
data
}
}
发起action:
dispatch(actionCreator(data));
Reducer
reducer具体描述了如何根据action更新state,并返回更新后的state。
function someReducer(state = initialState, action) {
switch(action.type) {
case 'string':
// 执行没有副作用的操作,这里不能直接更改原state,一般使用深复制生成新的state对象
...
return newState;// 返回新的更新后的state
default:
return state;// 返回原state
}
}
拆分reducer并将每个返回值合并为一个state
当reducer函数较复杂时可进行拆分,让每个子reducer分别处理部分state数据,并最终合并。
使用Redux提供的combineReducers()
实现:
import { combineReducers } from 'redux'
function someReducer(state, action) {}
function otherReducer(state, action) {}
export default combineReducers({
someReducer,
otherReducer
})
或者:
import { combineReducers } from 'redux'
import * as reducers from './reducers' // 包含所有reducer的js文件
const todoApp = combineReducers(reducers)
Store
使用合并后的reducer创建一个store:
import { createStore } from 'redux'
let store = createStore(todoApp); // todoApp是合并后的reducer
createStore()
的第二个参数是可选的, 用于设置 state 的初始状态。
使用创建好的 store 发起 action 更新state:
import { someAction,otherAction } from './actions'
store.dispatch(someAction(param))
store.dispatch(otherAction(otherParam))
获取当前state值:
store.getState()
监听state的更新,每次更新时执行操作,它返回一个函数用来注销监听器:
const unsubscribe = store.subscribe(() =>
console.log(store.getState())
)
// 停止监听 state 更新
unsubscribe();