1.Redux设计理念
Redux是将整个应用状态存储到一个地方上称为store,里面保存着一个状态树store tree,组件可以派发(dispatch)行为(action)给store,而不是直接通知其他组件,组件内部通过订阅store中的状态state来刷新自己的视图。
2. Redux三大原则
1 唯一数据源
整个应用的state都被存储到一个状态树里面,并且这个状态树,只存在于唯一的store中
2 保持只读状态
state是只读的,唯一改变state的方法就是触发action,action是一个用于描述以发生时间的普通对象
3 数据改变只能通过纯函数来执行
使用纯函数来执行修改,为了描述action如何改变state的,你需要编写reducers
connect
// (mapStateToProps = state => state, mapDispatchToProps = {}) => (WrapComponent) => {}: 就是个高阶组件,装饰WrapComponent组件
export const connect = (mapStateToProps = state => state, mapDispatchToProps = {}) => (WrapComponent) => {
return class ConnectComponent extends React.Component {
// 老式的上下文声明,constructor里面就可以拿到context
static contextTypes = {
store: PropTypes.object
}
constructor(props, context) {
super(props, context)
this.state = {
props: {}
}
}
componentDidMount() {
const {store} = this.context
store.subscribe(() => this.update())
this.update()
}
update() {
const {store} = this.context
//按照mapStateToProps声明的规则进行映射,拿到所需的状态对象
const stateProps = mapStateToProps(store.getState())
const dispatchProps = bindActionCreators(mapDispatchToProps, store.dispatch)
this.setState({
props: {
...this.state.props,
...stateProps,
...dispatchProps
}
})
}
render() {
<WrapComponent {...this.state.props} />
}
}
}
function bindActionCreators(creators,dispatch){
return Object.keys(creators).reduce((ret,item)=>{
ret[item] = bindActionCreator(creators[item],dispatch)
return ret
})
}
bindActionCreators = (creators,dispatch) => {
return Object.keys(creators).reduce((ret,item)=>{
ret[item] = bindActionCreator(creators[item],dispatch)
return ret
})
}
Provider
export class Provider extends React.Component{
// 老式上下文传递方式,childContextTypes和getChildContext,可以将{store:this.store}传递到子代去
static childContextTypes = {
store: PropTypes.object
}
getChildContext(){
return {store:this.store}
}
constructor(props, context){
super(props, context)
this.store = context.store
}
render() {
return this.props.children
}
}
thunk
const thunk = ({dispatch,getState})=>next=>action=>{
if (typeof action=='function') {
return action(dispatch,getState)
}
return next(action)
}