如何从函数组件传递状态,以便在use- context中使用它?



所以我试图在react.js中以一种状态的形式获得一些数据,我需要在useContext中使用它,这样我就可以执行Api调用,所以请如果有人可以帮助,那将是一个请<3,真的很有帮助,谢谢你

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

// 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>。并在<MyChildrenComponents />value可以。

,

为了提取value,我们使用useContext:

// MyChildrenComponents.js
import React, { useContext } from 'react';
import { MyContext } from './MyComponent.js';
const MyChildrenComponents = () => {
const { myState, setMyState } = useContext(MyContext);

// ...
}

你可以在这里(文档)阅读更多关于React上下文的信息。

相关内容

最新更新