React
redux 是(React全家桶)的核心成员
编写 react-redux 库关键在于两点:
- 创建一个 connect高阶函数完成对子孙组件的封装
- 真正意义上连接了 React和 Redux。
- 返回一个通过connect包裹后,完成数据更新后,封装的子组件。
- 创建一个 Provider组件完成对子孙组件的数据传递
- 在原应用组件上包裹一层外衣,使原来整个应用成为 Provider的子组件;
- 接收 Redux的 store作为 props
(this.props.store)
,通过 context对象传递数据给子孙组件。
import React from 'react';
import PropTypes from 'prop-types';
<-- 创建一个高阶函数,利用 context获取 store中的 sate的最新状态,再把此时 state的最新值传输给子组件,此时子组件拿到 参数对元素进行数据渲染-->
export let connect = (mapStateToProps, mapDispatchToProps) => (Component) => {
<-- 创建一个子组件外衣(Proxy),承接由高阶函数把 state的最新状态传输给子组件,子组件封装后的返回值 -->
return class Proxy extends React.Component {
<-- 子组件 contextTypes函数,用来放置从父组件一层层传递下来的数据 -->
static contextTypes = {
store: PropTypes.object
};
<-- props:承接父组件的行内样式属性,context:this.context,父组件中传递下来的数据 -->
constructor(props, context) {
super();
<-- context.store.getState() 的返回值是数据更新后 store里面最新的 state值 -->
this.state = {
...mapStateToProps(context.store.getState()),
...mapDispatchToProps(context.store.dispatch),
}
}
componentDidMount() {
<-- 将事件池中渲染过后的事件数据放入一个函数,便于参加生命周期函数,移除无用事件 -->
this.unsubscribe = this.context.store.subscribe(() => {
<-- 随时更新 this.context.store.getState() 的返回值 state -->
this.setState(mapStateToProps(this.context.store.getState()))
});
}
componentWillUnmount() {
、<-- 组件卸载时,触发生命周期函数,将事件池中的事件移除,提升组件性能 -->
this.unsubscribe();
}
render() {
<-- 返回值是:数据更新后 store里面最新的 state值,此时的返回值为封装后的子组件 -->
return <Component {
<-- ...{state:state} -->
...this.state
}
><Component>
}
}
};
<-- 创建一个父组件外衣(Provider),此组件中的 this.props的作用也相当于子组件用来放置父组件的行内属性,父组件封装后的返回值 -->
export class Provider extends React.Component{
<-- 定义子组件上下文的类型 -->
static childContextTypes = {
store:PropTypes.object
};
<-- 定义子组件上下文的数据 -->
getChildContext(){
return {store:this.props.store}
}
constructor(){
super();
}
render(){
<-- 返回值是:父组件中的返回值`<Provider>`里面包含的内容,相当于vue里面的(slot)插槽方法,通俗来讲此时父组件中的返回值`<Provider>`里面包含的内容里有什么,浏览器就渲染什么,试图就更新什么 -->
return this.props.children;
}
}