【问题标题】:How can I pass a state from a function component so i can use it in the use-Context如何从函数组件传递状态,以便可以在 use-Context 中使用它
【发布时间】:2021-10-09 13:08:18
【问题描述】:

所以我试图在 react.js 中以状态的形式获取一些数据,我需要在 useContext 中使用它,以便我可以执行 Api 调用,所以请如果有人可以提供帮助,那将是一个请

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: javascript reactjs react-hooks


【解决方案1】:

如果我正确理解你的问题,你可以这样做:

// MyComponent.js

import React, { useState, createContext } from "react";

// Note that you have to export the context to use it elsewhere
export const MyContext = createContext(null);

const MyComponent = () => {
 const [myState, setMyState] = useState();

 // Provider provides the context to components that are nested under it
 return (
  <MyContext.Provider value={{ myState: myState, setMyState: setMyState }}>
   <MyChildrenComponents />
  </MyContext.Provider>
 );
};

value 可以在提供程序下嵌套的任何组件中访问。在这种情况下,提供者是&lt;MyContext.Provider&gt;。而value 可以在&lt;MyChildrenComponents /&gt; 中访问。

--

为了提取value,我们使用useContext

// MyChildrenComponents.js

import React, { useContext } from 'react';
import { MyContext } from './MyComponent.js';

const MyChildrenComponents = () => {
  const { myState, setMyState } = useContext(MyContext);
  
  // ...
}

您可以阅读更多关于 React 上下文 here(文档)的信息。

【讨论】:

    猜你喜欢
    • 2018-09-01
    • 2017-05-20
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 2021-11-23
    相关资源
    最近更新 更多