简体   繁体   中英

React useContext() default value has not changed even I provide a value

Why is the UserContext default value has not changed even I specify a value in <UserContext.Provider>? How can I override the default value of the Context?

this is the App.jsx

import './App.css';
import React, { createContext } from 'react';
import ComponentB from './components/hooks/context/ComponentC';

function App() {
  return (
    <div className="App">
      <ComponentB />
    </div>
  );
}

export default App;

this is the ComponentB

import React, { createContext, useState } from 'react';
import ComponentC from './ComponentC';

export const UserContext = React.createContext('default');
export const ChannelContext = React.createContext('default');

const provider = UserContext.Provider;

function ComponentB() {
  return (
    <div>
      <provider value='Username'>
        <ComponentC />
      </provider>
    </div>
  );
}

export default ComponentB;

this is the ComponentC

import React from 'react';
import ComponentE from './ComponentE';

const ComponentC = () => {
  return <ComponentE />;
}

export default ComponentC;

this is the ComponentE

import React, { Component, useContext } from 'react';
import { UserContext, ChannelContext } from './ComponentB';

const ComponentE = () => {
  const username = useContext(UserContext);
  const channel = useContext(ChannelContext);

  return <div>username : {username} channel : {channel}</div>;
}

export default ComponentE;

In your App.jsx file, you say this:

import ComponentB from './components/hooks/context/ComponentC';
                ^                                           ^

Down the chain, this leads to this being rendered:

<div className="App">
  <div>
    username : {username} channel : {channel}
  </div>
</div>

As you can see, there's no provider.

Even still, if we fix this one character typo, the issue persists.

This is because you say

const provider = UserContext.Provider;

...
<provider>
  ...
</provider>

which isn't allowed.

If you do

<UserContext.Provider>
  ...
</UserContext.Provider>

it works.

https://codesandbox.io/s/wizardly-andras-csxxy?file=/src/App.js

Regarding the first issue, this is why you should do

export const MyComponent = () => <></>;
import { MyComponent } from "./MyComponent";

instead of

const MyComponent = () => <></>;
export MyComponent;
import MyComponent from "./MyComponent";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM