这是我在 React js 中的 URL
http://localhost:3000/meassger/student/1
我想1从 URL 中提取它是否是一个功能组件,我可以使用 ```useParams``
我收到这个错误
TypeError: Cannot read properties of undefined (reading 'params')
componentDidMount() {
console.log(this.props.match.params.id, "");
};
Run Code Online (Sandbox Code Playgroud)
您需要将其包装在 withRouter 中 - 将 URL 变量注入到您的 props 中。
您可以在此处找到示例:https ://stackoverflow.com/a/60316195/13063136
代码:
import React from "react";
import { withRouter } from "react-router";
class ShowTheID extends React.Component {
const { match } = this.props;
componentDidMount() {
console.log(match.params.id)
}
render() {
return <div>{match.params.id}</div>;
}
}
const ShowTheIDWithRouter = withRouter(ShowTheID);
Run Code Online (Sandbox Code Playgroud)
注意:除了包装组件之外,
withRouter您还需要确保您的路由已注册,并且您在路由路径中提到了 URL 参数,例如 path="/meassger/student/:id"
| 归档时间: |
|
| 查看次数: |
18165 次 |
| 最近记录: |