首页 > 解决方案 > React Context 不能使用 Provider

问题描述

我正在简化尝试使用 React更新上下文的过程。

我希望当我单击标题时Hello CodeSandbox,加载栏会显示context api数据。

代码示例: https ://codesandbox.io/s/vyq3r7k4o5

使用上下文加载

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>
  );
};

消费者

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>
    );
  }
}

标签: javascriptreactjsreact-context

解决方案


您的Loading组件应位于 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>
    );
  }
}

推荐阅读