自定义 redux & react-redux
redux
/*
redux模块:对象
1). redux模块整体是一个对象模块
2). 内部包含几个函数
createStore(reducer) 接收一个reducer函数,返回一个store对象 使用:createStore(reducer)
combineReducers() 接收一个包含多个reducer函数的对象,返回一个新的reducer函数 使用:combineReducers({count, msgs})
applyMiddleware() // 太难暂不实现
3). store对象的功能
getState() 得到内部管理state对象
dispatch(action) 分发action,会触发reducer调用,返回一个新的state,调用所有绑定的listener
subscibe(listener) 订阅一个state的监听器
*/
/*
创建store对象的函数
*/
export function createStore(reducer) { // 接收的是整合以后的reducer
let state // 内部管理的state
const listeners = [] // 用来缓存监听的数组容器,内部保存n个listener的数组
state = reducer(state, {type: '@@mini-redux/INIT'}) // 第一次调用reducer得到初始state值并保存
/*获取当前状态
得到内部管理state对象
*/
function getState() {
return state
}
/*分发消息
分发action,会触发reducer调用,返回一个新的state,调用所有绑定的listener
*/
function dispatch(action) {
state = reducer(state, action) // 调用reducer, 得到一个新的state
listeners.forEach(listener => listener()) // 调用listeners中所有的监视回调函数, 通知状态变化
}
/*订阅监听
订阅一个state的监听器
*/
function subscribe(listener) {
listeners.push(listener) // 将新的监听添加到监听缓存容器中
}
return {getState, dispatch, subscribe} // 向外暴露store对象
}
/*合并多个reducer的函数
接收一个包含多个reducer函数的对象,返回一个新的reducer函数
*/
export const combineReducers = (reducers) => {
// 返回一个reducer声明函数
return (state = {}, action) => { // 这是一个reducer,会传给createStore()
// 依次调用所有reducer函数,得到n个新的子状态,封装成对象并返回
const newState = {} // 准备一个用来保存所有新状态的容器对象
// 包含所有reducer函数名的数组: ['count', 'msgs']
const keys = Object.keys(reducers)
keys.forEach(key => { // 遍历
const childReducer = reducer[key] // 得到对应的子reduicer函数
const childState = state[key] // 得到对应的子state
const newChildState = childReducer(childState, action) // 执行reducer
newState[key] = newChildState // 整合,保存到新的总state中
})
return newState // 返回总的新state
}
}
/* 更好的写法 */
export const combineReducers = (reducers) => {
// 返回一个reducer声明函数
return (state = {}, action) => { // 这是一个reducer,会传给createStore()
// 依次调用所有reducer函数,得到n个新的子状态,封装成对象并返回
// 返回包含所有reducer状态的总state对象
return Object.keys(reducers).reduce((newState, reducerName) => {
// 调用对应的reducer函数得到对应的新state, 并保存到总state中
newState[reducerName] = reducers[reducerName](state[reducerName], action)
return newState
}, {})
}
}
// 调用
createStore(combineReducers({
count,
msgs
}))
react-redux
/*
1). react-redux模块整体是一个对象模块
2). 包含2个重要属性: Provider和connect
3). Provider
值: 组件类
作用: 向所有容器子组件提供全局store对象
使用: <Provider store={store}><Xxx/></Provider>
4). connect
值: 高阶函数
作用: 包装组件生成容器组件, 让被包装组件能与redux进行通信
使用: connect(mapStateToProps, mapDispatchToProps)(Xxx)
1). 理解
当你觉得多层传递props麻烦, 可以选择使用context
context是组件对象的一个属性, 它的值是一个对象
一个组件指定的context内数据, 所有层次子组件都可以读取到
如果可以尽量不用context, 你可以选择使用react-redux, react-redux内部就利用了context
2). 使用
父组件:
static childContextTypes = {
color: PropTypes.string
}
getChildContext() {
return {color: 'red'};
}
后代组件:
static contextTypes = {
color: PropTypes.string
}
render () {
this.context.color
}
*/
import React, {Component} from 'react'
import PropTypes from 'prop-types'
/*
react-redux模块: 对象, 包含以下属性:
1.Provider 组件类
2.connect 方法
*/
/*
1. Provider 组件类 为所有的容器子组件提供store(context)
<Provider store={store}>
<App />
</Provider>
*/
export class Provider extends Component {
static propTypes = {
store: PropTypes.object.isRequired // 声明当前组件接收store
}
// 声明向子组件提供哪些context数据
// 必须声明向子节点指定全局数据store
static childContextTypes = {
store: PropTypes.object.isRequired
}
// 指定向子组件指定全局数据store
// 为子组件提供包含store的context
getChildContext() {
return {store: this.props.store}; // 返回的就是context对象
}
render() {
/* 返回所有子节点(如果没有子节点返回undefined, 如果只有一个子节点它是对象, 如果有多个它是数组)
this.props.children 代表 Provider内部的所有子标签
如果没有子标签:undefined
如果只有一个子标签:对象
如果有多个子标签:数组 */
return this.props.children
}
}
/*
2. connect方法
用法:export default connect((state) => {}, {})(Xxx)
mapStateToProps 函数,用来确定一般属性
mapDispatchToProps 对象,用来确定函数属性,内部会使用dispatch
*/
export function connect(mapStateToProps = () => null, mapDispatchToProps = {}) {
// 返回函数(接收被包装组件类作为参数)
return (WrapComponent) => {
// 返回一个新的组件类(容器组件)
return class ConnectComponent extends Component {
// 声明接收全局store
// 声明获取context数据
static contextTypes = {
store: PropTypes.object.isRequired
}
// 构造函数的第2个参数为context对象
constructor(props, context) {
super(props)
console.log('constructor', this.context) // 此时组件对象中还没有context
const store = context.store // 得到store,从context中取出store
// 包含一般属性的对象
// 一般属性: 调用mapStateToProps函数得到包含所有需要传递一般属性的集合对象
const stateProps = mapStateToProps(store.getState())
// 包含函数属性的对象
// 分发action的函数属性: 调用自定义的整合函数生成包含多个分发action的函数的对象
const dispatchProps = this.bindActionCreators(mapDispatchToProps)
// 初始化状态, 包含所有需要传递给WrapComponent组件的一般属性
// 将所有的一般属性都保存到state中
this.state = {...stateProps}
// 将包含dispatch函数的对象保存在组件对象上(不用放到state中)
// 将所有函数属性的对象保存组件对象
this.dispatchProps = dispatchProps
}
/*
根据包含多个action creator的对象, 返回一个包含多个分发action的函数的对象
根据mapDispatchToProps返回一个包含分发action的函数的对象
*/
/* 版本1 */
bindActionCreators = (mapDispatchToProps) => {
const dispatchProps = {} // 准备一个保存分发action函数的对象容器
// 遍历每个action creator
Object.keys(mapDispatchToProps).forEach((key) => {
const actionCreator = mapDispatchToProps[key] // 得到某个action creator
//定义包含分发action代码的函数, 并只在到准备好的容器中
dispatchProps[key] = (...args) => { // 透传: 将函数接收到的参数,原样传内部函数调用
this.context.store.dispatch(actionCreator(...args))
}
})
return dispatchProps // 返回dispatch代码函数容器对象
}
/* 版本2 */
bindActionCreators = (mapDispatchToProps) => {
const keys = Object.keys(mapDispatchToProps)
return keys.reduce((preDispatchProps, key) => {
// 添加一个包含dispatch语句的方法
preDispatchProps[key] = (...args) => { // 透传: 将函数接收到的参数,原样传内部函数调用
// 分发action
this.context.store.dispatch(mapDispatchToProps[key](...args))
}
return preDispatchProps
}, {})
}
// 监听
componentDidMount() {
const store = this.context.store // 得到store
// 订阅监听
store.subscribe(() => {
// 一旦store中的state有变化, 更新组件状态, 从而导致被包装组件重新渲染
this.setState(mapStateToProps(store.getState()))
})
}
render() {
// 返回被包装组件标签, 传入整合的所有属性
return <WrapComponent {...this.state} {...this.dispatchProps}/>
}
}
}
}