手写redux

两个基本点: 1. 使用订阅发布模式实现createStore, 记住常用API: getState, dispatch, subscribe, 按图索骥 2. 利用react context实现Connect 对组件进行包装, 记住mapStateToProps, mapDispatchToProps

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
function createStore (reducer) {
let listens = [];
let dispatch = ({action, value})=>{
state = reducer(action, value)
listens.forEach((callback)=>{
callback(state)
})
}
let subscribe = (callback)=>{
listens.push(callback)
}
let getState = () => state;
dispatch({})
return { getState , dispatch, subscribe, }
}


let Store = createStore({})
Store.dispatch({a: 1})
Store.subscribe((newState)=>{
console.log(1)
})


const Connect = (mapStateToProps, mapDispatchToProps)=> (WrapComponent) => {
class Connect extends Component {
static contextProps = {
store: typeProps.object
}
constructor() {
this.state = {
allProps: {}
}
}
componentWillMount() {
const { store } = this.context;
this._updateState();
store.subscribe(()=>{
this._updateState();
})
}
_updateState() {
const { store } = this.context;
let newState = mapStateToProps ? mapStateToProps(store.getState()) : {}
let dispatchProps = mapDispatchToProps ? mapDispatchToProps(store.dispatch) : {}
this.setState({
allProps: {
...newState,
...this.props,
...dispatchProps
}
})
}
render() {
return(<WrapComponent {...this.state.allProps}/>)
}
}
return Connect
}