react-redux源码解读与学习之Provider
2017年12月22日351 browse
之前我有讲过redux源码系列,react-redux是把react和redux两个库结合起来的一个桥梁,因此在此之前你需要了解一些react和redux相关的知识。
- 如果你还不知道redux是什么,请先移步:redux中文文档 或者看看我之前的文章:redux v3.7.2源码解读与学习之compose
- 如果你还不知道react是什么,请先移步:react中文文档 英文文档
下面开始这篇文章的正题:react-redux
源码之Provider
我们先来看看react
的一个知识点:Context
参考链接:https://reactjs.org/docs/context.html
备注:官方推荐,我们平时开发的应用程序中尽量不要使用context,因为这是一个实验性的API,在未来的React版本中可能会被更改。如果你要坚持使用context,那么尽量将使用context的代码隔离到一小块地方并避免直接使用context API,这样以后API变更的时候更容易升级。
所以在平时开发中我们尽量不要使用此功能点,即使使用也应该封装到一个很集中的文件,以方便于以后api变动之后的升级。
下面这段代码是官网的一个例子,能很好的说明context用法:
const PropTypes = require('prop-types');
//孙子组件直接获取到context中的color值,不需要通过props一层一层的传递
class Button extends React.Component {
render() {
return (
<button style={{background: this.context.color}}>
{this.props.children}
</button>
);
}
}
//此代码必须
Button.contextTypes = {
color: PropTypes.string
};
class Message extends React.Component {
render() {
return (
<div>
{this.props.text} <Button>Delete</Button>
</div>
);
}
}
class MessageList extends React.Component {
getChildContext() {
return {color: "purple"};
}
render() {
const children = this.props.messages.map((message) =>
<Message text={message.text} />
);
return <div>{children}</div>;
}
}
//此代码必须
MessageList.childContextTypes = {
color: PropTypes.string
};
根据上面这个官方案例我们能够清晰的看出context
的使用,其中的几个知识点:
- 引入
prop-types
类型检测库,及其使用 childContextTypes
的使用
首先看Provider Api的使用:
从以上图片可以分析出,Provider 组件接收一个参数store ,和一个唯一的Child组件App
这个store值即为 redux createStore 方法返回的Object对象 ,格式为:
了解了以上的内容之后我们回头再来看react-redux的components/Provider.js文件源码:
代码也比较简单,我去掉了警告部分。
总结:
- 从上图中我们可以很明显的看出Provider是react的一个组件,
- 这个组件所干的事情就是使用了context,把传入的参数store注入到子孙组件中的context参数中,从而达到子孙组件都可以从context获取到store对象。
- Provider干的事情就这么多,它也遵守了官方的建议,把使用context集中到了Provider这个方法中,以便于以后Api更改后的升级。
博主
zane
发表于 2017-12-22 11:48:42,添加在了 react.js
标签下打赏
您的支持将鼓励我继续努力与分享。


评论
正在加载验证码......