javascript - 无法读取 React 中未定义的属性“参数”
问题描述
我是反应新手。我正在尝试使用react-router-dom
. 但无法获得参数
TypeError:无法读取未定义的属性“参数”。
我尝试了已经存在但没有任何帮助的解决方案。我犯了什么错误?有人可以向我解释吗?提前致谢。
Main
零件:
function App() {
return (
<div className="App">
<Router>
<Switch>
<Route path="/edit/:id" component={Edit} exact={true}>
<Edit />
</Route>
</Switch>
</Router>
</div>
);
}
export default App;
Edit
零件:
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>
)
}
Also, I don't know which React Router version you use, but if you are not using v6, you probably want to use the Route part like this:
<Router>
<Switch>
<Route path="/edit/:id" component={Edit} exact />
</Switch>
</Router>
推荐阅读
- spring - Spring Rest 和 JPA
- r - 如何使用 dplyr 第 2 部分将每日数据分组到数据框中的月份
- php - Symfony 3.4 - 软删除相关实体行后更新实体
- css - 如何将正文内容复制到元标题?
- android - imageview的Firebase“无内容提供者”错误
- spring-boot-actuator - Spring-boot - 在 HAL 浏览器的 /actuator 上找不到 httptrace
- cocoa - 检查 Cocoa 的大小写敏感性
- java - 如何检查Java中的属性(对象)是否为空
- python - 如何在 true 内每 x 秒运行一次代码 - python
- python - 生成二元组,但只生成名词和动词组合