Bug:useParams()钩子启动错误:TypeError:useContext(..)未定义



我正试图使用useParams()react钩子来检索参数,但我收到了以下错误:

TypeError: useContext(...) is undefined

这个错误实际上是由钩子文件抛出的,特别是这一行(第40行):


/modules/hooks.js:40
39 | 
> 40 |   const match = useContext(Context).match;
41 |   return match ? match.params : {};
42 | }

我的包含路由逻辑的App.js文件如下所示:


import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import { ThemeProvider } from "@material-ui/core";
import theme from "./views/config/theme";
import { routes } from "./views/config/routes";
import Header from "./views/components/common/Header";
import Footer from "./views/components/common/Footer";
function App() {
return (
<div>
<ThemeProvider theme={theme}>
<Router>
<Header />
<Switch>
{routes.map((route) => (
<Route exact path={route.path}>
{route.component()}
</Route>
))}
</Switch>
<Footer />
</Router>
</ThemeProvider>
</div>
);
}
export default App;

包含所有路由的routes.js文件如下所示:


import Dashboard from "../pages/Dashboard";
import UserDetails from "../pages/UserDetails";
export const routes: [
{
name: "Dashboard",
path: "/dashboard",
component: Dashboard,
access: "public",
},
{
name: "User details",
path: "/user/:id",
component: UserDetails,
access: "private",
},
];

这是UsersDetails组件文件,我正试图在其中使用useParams()钩子,它看起来像这样:


import { useParams } from "react-router-dom";
const UserDetails = () => {
const { id } = useParams();
return (
<div>
<p>{id}</p>
</div>
);
};
export default UserDetails;  

我正在使用:

NodeJS - 14.17.0

和:

"react": "^17.0.2"
"react-dom": "^17.0.2"
"react-router": "^5.2.0"
"react-router-dom": "^5.2.0"
"react-scripts": "4.0.3"

1。设置路线

首先,在路由中=>组件必须包装在开闭角括号中。例如,我的路线将如下所示:

const routes = [
{
name: "Dashboard",
path: "/dashboard",
component: <Dashboard />,
access: "public",
},
{
name: "User details",
path: "/user/:id",
component: <UserDetails />,
access: "private",
},
];

2.创建两个组件进行测试

接下来,我创建了两个类似的组件:

const Dashboard = () => {
return <h2>Dashboard</h2>;
}
const UserDetails = () => {
let { id } = useParams();
return <div style={{ fontSize: "50px" }}>
User Detail {id}
</div>;
}

3.包装应用程序组件

在AppComponent中,我们不需要调用组件函数(route.Component()),例如,如下所示:

const App = () => {
return (
<Router>
<div>
<Header />
<Switch>
{routes?.map((route) => <Route path={route.path}>
{route.component}
</Route>)}
</Switch>
</div>
</Router>
);
}

相关内容

  • 没有找到相关文章