无法读取 useParams 中未定义的属性“match”-React Hooks
2020-11-03
6379
我尝试在 React Router 中发送参数并出现以下错误
参考代码 在我的 Route.js 中,我添加了 browserRouter 和 Route
function AppRoute() {
const classes = useStyles();
return (
<BrowserRouter>
<div className={classes.root}>
<div className='App-header'>
<Grid container justify="center" className={classes.root} spacing={2} alignItems="center">
<Grid item xs={3}>
<Paper className={classes.paper} >
<Link to='/'>Dashboard</Link>
</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper} >
<Link to='/create'>Create</Link>
</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper} >
<Link to="/edit/john">Edit</Link>
</Paper>
</Grid>
<div>
<Switch>
<Route exact path="/" component={Dashboard} exact={true} />
<Route exact path="/create" component={Create} />
<Route path="/edit/:name">
<Edit />
</Route>
</Switch>
</div>
</Grid>
</div>
</div>
</BrowserRouter>
)
}
Edit.js
function Edit() {
const { name } = useParams();
return (
<div>
Name - {name}
</div>
)
}
1个回答
根据您收到的错误,我们可以得出以下结论:
无法读取未定义的属性“match”
如屏幕截图所示,这种情况发生在第 40 行。
const match = useContext(Context).match
这意味着调用的这一部分返回了
undefined
:
useContext(Context) === undefined
换句话说,这意味着
Context.Provider
在您的组件树的该点不可用。
您应该在由
<Route/>
呈现的组件内调用此方法。否则它将找不到
Context
,并且您会收到此错误。再检查一下。
来自: https://reactrouter.com/web/api/Hooks/useparams
import React from "react";
import ReactDOM from "react-dom";
import {
BrowserRouter as Router,
Switch,
Route,
useParams
} from "react-router-dom";
function BlogPost() {
let { slug } = useParams(); // IT'S CALLED INSIDE BlogPost
return <div>Now showing post {slug}</div>;
}
ReactDOM.render(
<Router>
<Switch>
<Route exact path="/">
<HomePage />
</Route>
<Route path="/blog/:slug">
<BlogPost /> {/* <<< AND BlogPost IS RENDERED INSIDE A <Route/> */}
</Route>
</Switch>
</Router>,
node
);
cbdeveloper
2020-11-06