简体   繁体   中英

React Context doesn't work using Provider

I am simplifying trying to update the context with React.

I would like that when I click the title Hello CodeSandbox the loading bar is displayed with the context api data.

Code example: https://codesandbox.io/s/vyq3r7k4o5

Loading using Context

export const LoadingState = {
  loading: false
};
const LoadingContext = React.createContext(LoadingState);

export const LoadingProvider = LoadingContext.Provider;
export const LoadingConsumer = LoadingContext.Consumer;

const LinearIndeterminate = function() {
  const { loading } = useContext(LoadingContext);
  return (
    <div>
      {loading && <LinearProgress color="secondary" />}
    </div>
  );
};

Consumer

class App extends PureComponent {
  state = {
    loading: false
  };

  add = () => {
    const currentState = this.state.loading;
    this.setState({ loading: !currentState });
  };

  render() {
    console.info(this.state);
    return (
      <div className="App">
        <h1 onClick={this.add}>Hello CodeSandbox</h1>
        <Loading />
        <LoadingProvider value={this.state}>
          {this.state.loading}
        </LoadingProvider>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    );
  }
}

Your Loading component should reside inside of App context provider.

working app: https://codesandbox.io/s/z6yjl04vjx

 class App extends PureComponent {
  state = {
    loading: false
  };

  add = () => {
    const currentState = this.state.loading;
    this.setState({ loading: !currentState });
  };

  render() {
    console.info(this.state);
    return (
      <div className="App">
        <h1 onClick={this.add}>Hello CodeSandbox</h1>
        <LoadingProvider value={this.state}>
           <Loading /> /* This line is moved. */
        </LoadingProvider>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    );
  }
}

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