我正试图提出一个泛型函数来将特定上下文包装在每个给定页面周围。 我在我的路线部分中进行了此操作,该部分将逐页地列出状态需求。理想情况下,这只是一个辅助功能。
import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Home from "./pages/Home";
import Analytics from "./pages/Analytics";
import { HomeProvider } from "./context/Home";
const wrapPageInContext = (Page, Context) => {
return (
<Context>
<Page />
</Context>
);
};
const ContextWrappedHome = () => {
return (
<HomeProvider>
<Home />
</HomeProvider>
);
};
export const MainRoutes = () => (
<BrowserRouter>
<Switch>
// This fails! :(
<Route
exact
path="/home"
component={wrapPageInContext(Home, HomeProvider)}
/>
// This works!!
<Route
exact
path="/home"
component={ContextWrappedHome}
/>
<Route exact path="/Analytics" component={<Analytics />
</BrowserRouter>
);
答案 0 :(得分:1)
您的wrapPageInContext
函数需要返回一个组件,如下所示:
const wrapPageInContext = (Page, Context) => () => {
return (
<Context>
<Page />
</Context>
);
};
或者更明确一点:
const wrapPageInContext = (Page, Context) => {
const Wrapper = () => (
<Context>
<Page />
</Context>
)
return Wrapper
};