Javascript 使用提供程序时,React上下文不起作用
我正在简化尝试使用React更新 我希望当我单击标题Hello CodeSandbox时,加载栏会显示上下文api数据 代码示例: 使用上下文加载 消费者 加载组件应位于应用程序上下文提供程序内部 工作应用程序:Javascript 使用提供程序时,React上下文不起作用,javascript,reactjs,react-context,Javascript,Reactjs,React Context,我正在简化尝试使用React更新 我希望当我单击标题Hello CodeSandbox时,加载栏会显示上下文api数据 代码示例: 使用上下文加载 消费者 加载组件应位于应用程序上下文提供程序内部 工作应用程序: 谢谢你的回答。这令人失望。因为我希望在全局路由上加载,然后编辑来自任何组件的值。我想我真的得用Mobx了 export const LoadingState = { loading: false }; const LoadingContext = React.createCont
谢谢你的回答。这令人失望。因为我希望在全局路由上加载,然后编辑来自任何组件的值。我想我真的得用Mobx了
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>
);
}
}
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>
);
}
}