首页 > 解决方案 > 在顶层使用 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;

标签: reactjsreact-hooksuse-context

解决方案


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.


推荐阅读