javascript - 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>
);
}
}
解决方案
您的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>
);
}
}
推荐阅读
- django - 如何在 django 中接收 http 帖子
- wpf - WPF取消带有消息框的选项卡选择
- c# - 无法访问我的 Asp.Net Core 项目中的帮助程序类中的 Session 对象
- ios - ARkit 在不重新启动会话的情况下删除无限平面?
- sql - 未找到 Greenplum CTE - 错误 [XX000] (allpaths.c:904)
- jquery - 如何使用 JQuery 从表中选择第一行
- java - 为什么这个人为的 Java 代码会死锁?
- javascript - response.forEach(function(data) 其中 response 是一个 json 双向
- javascript - 为什么“未处理的承诺拒绝”是一件事?
- c - 来自 csv 文件的指针和结构