reactjs - 在顶层使用 useContext 访问当前状态
问题描述
我有一个包含一组复选框、单选按钮和一个按钮的表单。
每次我更新复选框或单选按钮的值时,它都会调度一个更新我的状态的事件。我可以通过单击我的按钮组件来查看此状态:<Button context={ExampleContext} />
但是,我似乎无法通过添加相同的代码片段在父容器中以相同的方式访问我的状态,因为它只是返回未定义,这与我在 Button 组件中的逻辑相同,所以我不确定为什么它不工作。
我显然做错了什么,但我不确定是什么。如何state
从父容器中访问我的?
我在这里也有一个工作示例:https ://codesandbox.io/s/elegant-minsky-0i4yx
谢谢你的帮助!
// This doesn't seem to work
const { state } = useContext(ExampleContext);
<button onClick={() => console.log(state)}>See State</button>
import React from "react";
import Checkbox from "./Checkbox";
import Radio from "./Radio";
import Button from "./Button";
import { ExampleProvider, ExampleContext } from "./ExampleContext";
const { useContext } = React;
const Form = () => {
const { state } = useContext(ExampleContext);
return (
<ExampleProvider>
<Checkbox context={ExampleContext} />
<Radio context={ExampleContext} />
<Button context={ExampleContext} />
<button onClick={() => console.log(state)}>See State</button>
</ExampleProvider>
);
};
export default Form;
解决方案
Your useContext
hook is not inside the ExampleProvider
context Provider.
You can fix it like this
const Form = () => {
const { state } = useContext(ExampleContext);
return (
<>
<Checkbox context={ExampleContext} />
<Radio context={ExampleContext} />
<Button context={ExampleContext} />
<button onClick={() => console.log(state)}>See State</button>
</>
);
};
const FormWrapper = () => {
return (
<ExampleProvider>
<Form />
</ExampleProvider>
);
};
export default FormWrapper;
Look at this blogpost if you need to learn about the best way to handle the state management with React context API.
推荐阅读
- vue.js - 如何确保我的指令运行一个函数?
- google-bigquery - 使用适用于 Spark 的 BigQuery 连接器时,我可以发出查询而不是指定表吗?
- git - 包含一个项目的所有存储库的列表
- android - react native中Text组件的accessibility,accessibilityLabel和accessibilityHint属性有什么区别?
- angular - Openlayers 3:无法在 Angular 5 应用程序中选择功能
- javascript - 如何在 riot-lol-api npm 包中使用缓存?
- svn - TortoiseSVN 有什么方法可以增量构建我的提交吗?
- http - 为 Feature-Policy HTTP 标头设置默认值
- wpf - 如何让窗口始终在桌面上
- python - 数组 vs 对象 - Python 中什么更快