Redux 是一个 JS 的状态容器 ,用来统一化管理状态。
Redux 三大特点 :
1 . 单一数据源:
整个应用的 state 都被储存在一颗 Object tree 中 ,并且这个 object tree 只存在于唯一一个 store 中。
2 . State是只读的:
唯一改变 state 的方法就是触发 action ,action 是一个用于描述已发生事件的普通对象 。
3 . 使用纯函数来执行更新 State :
为了描述 action 如何改变 state ,需要编写 reducers 。reducers 是一些纯函数 ,它接收先前的state 和 action ,并返回新的 state 。
Redux 组成部分 :
1 . State 状态 :
2 . action 事件 :
action 是把数据从组件传到 store 的载体 ,它是 store 的唯一数据来源 ,可以在组件里面通过 store . dispatch( ) 来派发一个事件 ,把数据传给 store 。
- action 本质上就是一个 JS 对象
- action 对象内部必须要有一个 type 属性来描述要执行的动作 ,通常是一个字符串常量 。
- 除了 type 之外 ,action 的其它结构可以随便定义。
- 在项目中 ,通常使用 函数来创建 action 对象 。
function addCreateAction(params){
return {
type : ' add ',
...params
}
}
3 . reducer
Reducer 本身就是一个函数 ,用来响应派发过来的action ,经过处理 ,然后再把更新过后的 state 返回给 store ,必须有 return 返回值 !
- reducer 函数接收两个参数 ,第一个是先前的 state ,第二个是 事件action对象 。
4 . store
把 action 和 reducer 联系在一起的对象
- store . dispatch( ) 派发事件对象
- store . getState( ) 获取 State (通常在 store . subscribe( ) 中使用 ,用来获取更新过后的新状态)
- store . subscribe( ) 注册监听
store 的创建 :
const store = createStore(reducers);