【发布时间】:2021-10-09 13:08:18
【问题描述】:
所以我试图在 react.js 中以状态的形式获取一些数据,我需要在 useContext 中使用它,以便我可以执行 Api 调用,所以请如果有人可以提供帮助,那将是一个请
【问题讨论】:
-
请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
标签: javascript reactjs react-hooks
所以我试图在 react.js 中以状态的形式获取一些数据,我需要在 useContext 中使用它,以便我可以执行 Api 调用,所以请如果有人可以提供帮助,那将是一个请
【问题讨论】:
标签: javascript reactjs react-hooks
如果我正确理解你的问题,你可以这样做:
// 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 可以在提供程序下嵌套的任何组件中访问。在这种情况下,提供者是<MyContext.Provider>。而value 可以在<MyChildrenComponents /> 中访问。
--
为了提取value,我们使用useContext:
// MyChildrenComponents.js
import React, { useContext } from 'react';
import { MyContext } from './MyComponent.js';
const MyChildrenComponents = () => {
const { myState, setMyState } = useContext(MyContext);
// ...
}
您可以阅读更多关于 React 上下文 here(文档)的信息。
【讨论】: