Fix false positive context warning when using an old React (#13850)

This commit is contained in:
Dan Abramov
2018-10-14 15:35:52 +01:00
committed by GitHub
parent 4773fdf7cd
commit 9ea4bc6ed6
2 changed files with 34 additions and 7 deletions

View File

@@ -1118,13 +1118,18 @@ function updateContextConsumer(
// in DEV mode if this property exists or not and warn if it does not.
if (__DEV__) {
if ((context: any)._context === undefined) {
if (!hasWarnedAboutUsingContextAsConsumer) {
hasWarnedAboutUsingContextAsConsumer = true;
warning(
false,
'Rendering <Context> directly is not supported and will be removed in ' +
'a future major release. Did you mean to render <Context.Consumer> instead?',
);
// This may be because it's a Context (rather than a Consumer).
// Or it may be because it's older React where they're the same thing.
// We only want to warn if we're sure it's a new React.
if (context !== context.Consumer) {
if (!hasWarnedAboutUsingContextAsConsumer) {
hasWarnedAboutUsingContextAsConsumer = true;
warning(
false,
'Rendering <Context> directly is not supported and will be removed in ' +
'a future major release. Did you mean to render <Context.Consumer> instead?',
);
}
}
} else {
context = (context: any)._context;

View File

@@ -1584,6 +1584,28 @@ Context fuzz tester error! Copy and paste the following line into the test suite
);
});
// False positive regression test.
it('should not warn when using Consumer from React < 16.6 with newer renderer', () => {
const BarContext = React.createContext({value: 'bar-initial'});
// React 16.5 and earlier didn't have a separate object.
BarContext.Consumer = BarContext;
function Component() {
return (
<React.Fragment>
<BarContext.Provider value={{value: 'bar-updated'}}>
<BarContext.Consumer>
{({value}) => <div actual={value} expected="bar-updated" />}
</BarContext.Consumer>
</BarContext.Provider>
</React.Fragment>
);
}
ReactNoop.render(<Component />);
ReactNoop.flush();
});
it('should warn with an error message when using nested context consumers in DEV', () => {
const BarContext = React.createContext({value: 'bar-initial'});
const BarConsumer = BarContext;