React 路由器:useParams() returns 即使在解构时也未定义
React router: useParams() returns undefined even when destructured
我在 React 中使用 useParams 挂钩。我有一个要从 URL.
加载 ID 的组件
import React from 'react';
import { useParams } from 'react-router-dom'
const FakeGame = () => {
let { thisId } = useParams();
console.log(thisId);
console.log(useParams());
return (
<h1>This ID is: {thisId}</h1>
)
}
export default FakeGame
useParams() 控制台日志显示了我想要的对象数据,但解构它 returns 未定义。我在应用程序中有上一级路线:
<Link to="/">Home</Link>
<Routes>
<Route path="/:id" element={<FakeGame currentId={currentId}/>}></Route>
<Route path="/" element={<Home currentId={currentId} setCurrentId={setCurrentId}/>} />
</Routes>
并且 Link 到 Games 组件中的 FakeGame 组件:
const Games = ({ setCurrentId }) => {
const games = useSelector((state) => state.games);
return (
!games.length ? <CircularProgress /> : (
<Grid className={mergeClasses.container} container alignItems="stretch" spacing={3}>
{games.map((game) => (
<Grid key={game._id} item xs={12} sm={6}>
<Link to={`/${game._id}`}>FAKE GAME</Link>
<Game game={game} setCurrentId={setCurrentId}/>
</Grid>
))}
</Grid>
)
)
}
我这样做正确吗?
我的文件结构是
- App.js
+ components
- FakeGame.js
+ Games
- Games.js
在这一行中,您将参数的名称声明为“id”:
<Route path="/:id" element={<FakeGame currentId={currentId}/>}></Route>
因此,“thisId”的解构 returns 未定义,因为没有匹配 属性。将上面的行更改为 ..path=/:thisId
..(不推荐)或将 thisId
更改为 id
。
还要阅读 destructuring
我在 React 中使用 useParams 挂钩。我有一个要从 URL.
加载 ID 的组件import React from 'react';
import { useParams } from 'react-router-dom'
const FakeGame = () => {
let { thisId } = useParams();
console.log(thisId);
console.log(useParams());
return (
<h1>This ID is: {thisId}</h1>
)
}
export default FakeGame
useParams() 控制台日志显示了我想要的对象数据,但解构它 returns 未定义。我在应用程序中有上一级路线:
<Link to="/">Home</Link>
<Routes>
<Route path="/:id" element={<FakeGame currentId={currentId}/>}></Route>
<Route path="/" element={<Home currentId={currentId} setCurrentId={setCurrentId}/>} />
</Routes>
并且 Link 到 Games 组件中的 FakeGame 组件:
const Games = ({ setCurrentId }) => {
const games = useSelector((state) => state.games);
return (
!games.length ? <CircularProgress /> : (
<Grid className={mergeClasses.container} container alignItems="stretch" spacing={3}>
{games.map((game) => (
<Grid key={game._id} item xs={12} sm={6}>
<Link to={`/${game._id}`}>FAKE GAME</Link>
<Game game={game} setCurrentId={setCurrentId}/>
</Grid>
))}
</Grid>
)
)
}
我这样做正确吗?
我的文件结构是
- App.js
+ components
- FakeGame.js
+ Games
- Games.js
在这一行中,您将参数的名称声明为“id”:
<Route path="/:id" element={<FakeGame currentId={currentId}/>}></Route>
因此,“thisId”的解构 returns 未定义,因为没有匹配 属性。将上面的行更改为 ..path=/:thisId
..(不推荐)或将 thisId
更改为 id
。
还要阅读 destructuring