正因为有了前面的偷懒带来的便捷,所以才有带出来了react-redux库的盛行。也正是react-redux让redux和react的结合更加的紧密舒适。
import Provider from './Provider';
import connect from './connect';
export {
Provider,
connect
}
import React from 'react';
let ReactReduxContext = React.createContext();
export default ReactReduxContext;
import React from 'react';
import ReactReduxContext from './Context'
export default function(props) {
return (
<ReactReduxContext.Provider value={{store: props.stroe}}>
</ReactReduxContext.Provider>
)
}
- 这个用的高阶组件
- 1.从上下文中获取到Context {store}
- 2.从store.getState()=>mapStateToProps=>对象成为OldComponent的属性对象
- 3.负责订阅store状态变化事件,当仓库状态发生改变之后,要刷新当组件以及 OldComponent
- 4.把actions进行绑定,然后把绑定后的结果boundActions作为属性对象传递给OldComponent
import React { useContext, useState, UseEffect } from 'react';
import ReactReduxContext from './Context';
import { bindActionCreators } from 'redux';
export default function(mapStateToProps, mapDispatchToProps) {
return function (OldComponent) {
return function(props) {
let ctx = useEffect(ReactReduxContext);
let [state, setState] = useState(mapStateToProps(context.store.getState()));
let [boundActions] = useState(() =>bindActioncreators(mapDispatchToProps, context.stroe.dispatch));
useEffect(() => {
return context.store.subscribe(() => {
setState(mapStateToProps(context.store.getState())
})
},[])
return <OldComponent {...state} {...boundActions}>
}
}
}