【问题标题】:useContext is not working in my react codeuseContext 在我的反应代码中不起作用
【发布时间】:2021-06-17 10:54:44
【问题描述】:

应用组件:

    import React,{createContext} from "react";
    import "./style.css";
    import A from "./A";
    
    export const userContext =createContext();
    
    function App() {
      return (
        <userContext.Provider name={"samuel"}>
          <div>
            <A />
          </div>
        </userContext.Provider>
      );
    }
    export default App;

组件 A

    import React from 'react';
    import B from './B';
    function A(){
      return (<div>
      <h3>Component A </h3>
      <B />
      </div>)
    }
    
    export default A;

组件 B:

        import React, { useContext } from "react";
        import {userContext} from "./App";
    
    function B() {
      const name = useContext(userContext);
      return (
        <div>
          <h3>Component B{name} </h3>
        </div>
      );
    }
    
    export default B;

我在 App 组件中传递的上下文值没有在组件 B 中被消耗。

上下文用于将数据直接传递给组件,而不是传递给目标组件路径中的每个组件。 这样不需要数据的组件就无法访问它。 我在接收器组件中使用 useContext 挂钩而不是 Context.consumer api。

【问题讨论】:

    标签: reactjs use-context


    【解决方案1】:

    您必须将value 传递给Provider,在这种情况下您想要传递一个字符串,而您之前传递的对象是错误的关键字name

    我发现的另一个问题是您使用B 从上下文中提取value,但您没有将其置于可以访问上下文的组件的范围内:

    function App() {
      return (
        <userContext.Provider value="samuel">
          <div>
            <A />
            <B />
          </div>
        </userContext.Provider>
      );
    }
    export default App;
    

    现在可以使用了,您可以查看codesandbox

    【讨论】:

    • 是的,它有效。我有疑问,即使我传递对象,它也只有在我指定关键字值时才有效。是否必须在提供程序中提及 value 关键字?我们不能使用自己的命名就像我在我的代码中提到的 是否必须提供
    • @SamuelT 还有this video 很好地解释了如何通过更复杂的示例使用useContext 钩子
    • @SamuelT 你必须使用关键字value
    猜你喜欢
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 2018-01-10
    • 2023-03-24
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多