01 什么是状态管理
单向数据流->嵌套地域 解决的问题:跨组件之间的数据通信和状态共享
02 React状态管理简介
- Local State (组件级别的状态管理)
- Context (provider consume 粒度不可控、包裹、造成不必要的渲染)
- Redux (Flux 演变来的)
03 实现一个简易的状态管理工具
本质上都是[[发布订阅模式|发布/订阅模式]]
04 Redux在项目中的实践
// 实现一个简单的状态管理工具
export default class CreateStore {
constructor(reducer, initState) {
this.reducer = reducer
this.state = initState
this.listeners = []
this.isDispatching = false
}
getState() {
return this.state
}
dispatch(action) {
this.state = this.reducer(this.state, action)
this.listeners.forEach(listener => listener())
}
subscribe(listener) {
this.listeners.push(listener)
return function unsubscribe() {
const index = this.listeners.indexOf(listener)
this.listeners.splice(index, 1)
}
}
}