【发布时间】:2020-05-03 18:17:47
【问题描述】:
试图在似乎需要传入一个值的应用程序上实现全局上下文,其目的是 API 将返回一个组织列表到可用于显示和后续 API 调用的上下文。
当尝试将 <Provider> 添加到 App.tsx 时,应用程序抱怨该值尚未定义,而我正在使用 useEffect() 模拟 API 响应。
代码如下:
类型types/Organisations.ts
export type IOrganisationContextType = {
organisations: IOrganisationContext[] | undefined;
};
export type IOrganisationContext = {
id: string;
name: string;
};
export type ChildrenProps = {
children: React.ReactNode;
};
上下文contexts/OrganisationContext.tsx
export const OrganisationContext = React.createContext<
IOrganisationContextType
>({} as IOrganisationContextType);
export const OrganisationProvider = ({ children }: ChildrenProps) => {
const [organisations, setOrganisations] = React.useState<
IOrganisationContext[]
>([]);
React.useEffect(() => {
setOrganisations([
{ id: "1", name: "google" },
{ id: "2", name: "stackoverflow" }
]);
}, [organisations]);
return (
<OrganisationContext.Provider value={{ organisations }}>
{children}
</OrganisationContext.Provider>
);
};
用法App.tsx
const { organisations } = React.useContext(OrganisationContext);
return (
<OrganisationContext.Provider>
{organisations.map(organisation => {
return <li key={organisation.id}>{organisation.name}</li>;
})}
</OrganisationContext.Provider>
);
问题 #1:
Property 'value' is missing in type '{ children: Element[]; }' but required in type 'ProviderProps<IOrganisationContextType>'.
问题 #2:
列表未在App.tsx 上呈现
代码沙盒:https://codesandbox.io/s/frosty-dream-07wtn?file=/src/App.tsx
【问题讨论】:
标签: reactjs typescript react-context