// CreateStore
function createStore(reducer, initialState = {}) {
// currentState就是那个数据
let currentState = initialState;
let listener = () => { };
function getState() {
return currentState;
}
function dispatch(action) {
console.log(action)
currentState = reducer(currentState, action); // 更新数据
listener(currentState); // 执行订阅函数
return action;
}
function subscribe(newListener) {
listener = newListener;
// 取消订阅函数
return function unsubscribe() {
listener = () => { };
};
}
return {
getState,
dispatch,
subscribe
};
}
// store && reducer
const store = createStore(function(state={}, action) {
switch (action.type){
case 'update':
return {...state, ...action.data}
default:
return state
}
});
// entry 入口
export default class Root extends Component {
render() {
return (
<Provider value={store}>
<Route path="/" component={Header} />
</Provider>
)
}
}
// Connect
export default function connect(mapStateToProps, mapDispatchToProps) {
return function (WrappedComponent) {
class Connect extends React.Component {
constructor(props) {
super(props)
this.store = {}
this.handleStoreChange.bind(this)
}
componentDidMount() {
// 组件加载完成后订阅store变化,如果store有变化则更新UI
this.unsubscribe = this.store.subscribe(this.handleStoreChange);
}
componentWillUnmount() {
// 组件销毁后,取消订阅事件
this.unsubscribe();
}
handleStoreChange(storeVal) {
// 更新之后的storeVal
console.log(storeVal)
// 更新UI
this.forceUpdate();
}
render() {
return (
<Consumer>{
( store ) => {
this.store = store;
return <WrappedComponent
{...this.props}
{...mapStateToProps(store.getState())} // 参数是store里面的数据
{...mapDispatchToProps(store.dispatch)} // 参数是store.dispatch
/>
}
}</Consumer>
);
}
}
Connect.contextTypes = {
store: PropTypes.object
};
return Connect;
};
}
// Children || Grandson
function mapStateToProps(state) {
return {
}
}
function mapDispatchToProps(dispatch) {
return {
updateStore: function(data) {
console.log(data)
dispatch({type: 'update', data})
}
}
}
const Header = connect(
mapStateToProps,
mapDispatchToProps
)(_Header);