我正在尝试在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>
)
}
答案 0 :(得分:0)
从您得到的错误中,我们可以得出以下结论:
Cannot read property 'match' of undefined
这发生在第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
);