React的React.createContext()源码解析(四)

时间:2023-01-30 05:53:44

一.产生context原因

从父组件直接传值到孙子组件,而不必一层一层的通过props进行传值,相比较以前的那种传值更加的方便、简介。

二.context的两种实现方式

1.老版本(React16.x前)

//根组件
class MessageList extends React.Component {
//getChildContext函数,返回一个context对象
getChildContext() {
return { color: 'purple', text: 'item text' }
}
render() {
return (
<div>
<Message text="this is MessageList" />
</div>
)
}
}
//指定context结构类型 如果不写 产生错误
//import T from 'prop-types';
MessageList.childContextTypes = {
color: T.string,
text: T.string,
}
//中间组件
class Message extends React.Component {
render() {
return (
<div>
<MessageItem />
</div>
)
}
}
//孙子组件(接收组件)
class MessageItem extends React.Component {
render() {
//this.context获取上下文
return (
<div>
{this.context.text}
</div>
)
}
}
//孙子组件声明 接收context结构类型 如果contextTypes没有定义 context将是一个空对象
MessageItem.contextTypes = {
text: T.string
}

为什么会被摒弃?

  因为childContext对下层的组件影响太大了,即使子孙组件没有用到childContext,子孙组件仍然要进行更新,严重影响了性能 

2.新版本(React16.x后)

//创建两个组件 Provider,Consumer
//let {Provider,Consumer}=React.createContext(defaultValue); //defaultValue可以设置共享的默认数据 当Provider不存在的时候 defaultValue生效
const { Provider, Consumer } = React.createContext({ theme: "green" }) // 这里MessageList render(){<Content />}
class MessageList extends React.Component {
render() {
//Procider组件遍历子组件,并且有一个属性value,且value相当于旧版本的getChildContext()的返回的context对象 用来提供数据
return (
<Provider value={{ theme: "pink" }}>
<Content />
</Provider>
)
}
}
//中间组件
function Content() {
return (
<div>
<Button />
</div>
)
}
//接收组件,如果子组件是Consumer的话,将value作为参数值,传递给新创建的Consumer,渲染一个函数组件
function Button() {
return (
<Consumer>
{({ theme }) => (
<button
style={{ backgroundColor: theme }}>
Toggle Theme
</button>
)}
</Consumer>
)
}

注意:将undefined传递给<Provider>value时,createContext中的defaultValue不会生效,Consumervalue显示空值

三,React.createContext()源码解析

    //calculateChangedBits方法,使用Object.is()计算新老context的一个变化
function createContext(defaultValue, calculateChangedBits) {
if (calculateChangedBits === undefined) {
calculateChangedBits = null;
} else {
{
!(calculateChangedBits === null || typeof calculateChangedBits === 'function') ? warningWithoutStack$1(false, 'createContext: Expected the optional second argument to be a ' + 'function. Instead received: %s', calculateChangedBits) : void 0;
}
} var context = {
//context的$$typeof在createElement中的type对象中存储的
$$typeof: REACT_CONTEXT_TYPE,
//作为支持多个并发渲染器的解决方法 我们将一些渲染器作为主要渲染器 其他渲染器为辅助渲染器
_calculateChangedBits: calculateChangedBits,
//我们希望有两个并发渲染器:主要和次要
//辅助渲染器将自己的context的value存储在单独的字段里
//_currentValue和_currentValue2作用一样,只是作用平台不同
_currentValue: defaultValue, //Provider的value属性
_currentValue2: defaultValue,
//用来追踪context的并发渲染器的数量
_threadCount: 0,
// These are circular
Provider: null,
Consumer: null
}; //context.Provider的_context指向context对象
context.Provider = {
$$typeof: REACT_PROVIDER_TYPE,
_context: context
};
var hasWarnedAboutUsingNestedContextConsumers = false;
var hasWarnedAboutUsingConsumerProvider = false; {
// A separate object, but proxies back to the original context object for
// backwards compatibility. It has a different $$typeof, so we can properly
// warn for the incorrect usage of Context as a Consumer.
var Consumer = {
$$typeof: REACT_CONTEXT_TYPE,
_context: context,
_calculateChangedBits: context._calculateChangedBits
}; // $FlowFixMe: Flow complains about not setting a value, which is intentional here Object.defineProperties(Consumer, {
Provider: {
get: function () {
if (!hasWarnedAboutUsingConsumerProvider) {
hasWarnedAboutUsingConsumerProvider = true;
warning$1(false, 'Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
} return context.Provider;
},
set: function (_Provider) {
context.Provider = _Provider;
}
},
_currentValue: {
get: function () {
return context._currentValue;
},
set: function (_currentValue) {
context._currentValue = _currentValue;
}
},
_currentValue2: {
get: function () {
return context._currentValue2;
},
set: function (_currentValue2) {
context._currentValue2 = _currentValue2;
}
},
_threadCount: {
get: function () {
return context._threadCount;
},
set: function (_threadCount) {
context._threadCount = _threadCount;
}
},
Consumer: {
get: function () {
if (!hasWarnedAboutUsingNestedContextConsumers) {
hasWarnedAboutUsingNestedContextConsumers = true;
warning$1(false, 'Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
} return context.Consumer;
}
}
}); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty context.Consumer = Consumer;
} {
context._currentRenderer = null;
context._currentRenderer2 = null;
}
//返回一个context对象
return context;
}

返回的context内容:

React的React.createContext()源码解析(四)