我是 React 新手。我正在尝试使用 react-router-dom
通过 URL 传递值。但无法获取参数
TypeError: Cannot read property 'params' of undefined.
我尝试了现有的解决方案,但没有任何帮助。我犯了什么错误?有人可以向我解释一下吗?提前致谢。
主要
组件:
function App() {
return (
<div className="App">
<Router>
<Switch>
<Route path="/edit/:id" component={Edit} exact={true}>
<Edit />
</Route>
</Switch>
</Router>
</div>
);
}
export default App;
编辑
组件:
class Edit extends Component {
constructor(props) {
super(props);
this.state = {
id: this.props.match.params.id
};
}
render() {
return <h2>Edit Page</h2>;
}
}
export default Edit;
最佳答案
注意:我的答案是 useParams
因为你原来的问题涉及它。除此之外,如果您必须使用类组件,通常 this.props.match.params.id
应该可以工作,因为您通过 Route
使用组件.
您应该使用useParams
在你的Edit
组件,它应该是一个功能组件。
function Edit() {
const { id } = useParams();
return (
<div>{id}</div>
)
}
另外,我不知道你使用的是哪个 React Router 版本,但是如果你没有使用 v6,你可能想使用这样的 Route 部分:
<Router>
<Switch>
<Route path="/edit/:id" component={Edit} exact />
</Switch>
</Router>
关于javascript - 无法读取React中未定义的属性 'params',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60488807/