React Context使用提供程序不起作用

时间:2019-03-22 12:11:22

标签: javascript reactjs react-context

我正在简化尝试用React更新context的过程。

我希望在单击标题categories = WebDriverWait(driver, 10).until( EC.visibility_of_all_elements_located((By.XPATH, '//div[@class="mainCatEntry"]/div[@class="Description"]'))) 时显示加载栏,其中包含Hello CodeSandbox数据。

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

使用上下文加载

context api

消费者

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

1 个答案:

答案 0 :(得分:1)

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