这是我在react js中的URL
http://localhost:3000/meassger/student/1
我想从 URL 中提取
1
,如果它是一个功能组件,我可以使用``useParams``
我收到此错误
TypeError: Cannot read properties of undefined (reading 'params')
componentDidMount() {
console.log(this.props.match.params.id, "");
};
在功能组件中,使用
const history = useHistory()
const studentId = history?.location?.pathname.split('/')[3]
在类组件中,使用
const studentId = window.location.href.split('/')[3]
您需要将其包装在 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);
注意:除了将组件包装在
中之外,您还需要确保您的路由已注册,并且您在路由路径中提到了 URL 参数,例如 path="/meassger/student/:id"withRouter
假设我们有一个像http://localhost:3000/student/:studentId这样的url,我们需要从这个url中获取studentId参数
在功能组件中,我们可以这样做
import React from 'react';
import { useParams } from 'react-router-dom';
const Student = () => {
const { studentId } = useParams();
return (
<div>StudentId: { studentId }</div>
);
}
export default Student;
在基于类的组件中,我们可以这样做
import React, { Component } from 'react';
class Student extends Component {
render() {
const { studentId } = this.props.match.params;
return (
<div>StudentId: { studentId }</div>
);
}
}
export default Student;
或者,您可以与路由器 HOC 一起使用。通过这样做,您还可以访问位置和历史道具。
import React, { Component } from 'react';
import { withRouter } from "react-router";
class Student extends Component {
render() {
const { location, history } = this.props;
return (
<React.Fragment>
<div>StudentId: { match.studentId }</div>
<div>Path: {location.pathname}</div>
</React.Fragment>
);
}
}
const StudentWithRouter = withRouter(Student);
好的。我有同样的问题,这就是我解决它的方法。 我创建了一个名为 getParams.jsx 的单独组件
getParams.jsx
import React from 'react'
import { useParams } from 'react-router-dom'
function getParams() {
return (
<AnyComponent
{...props}
params={params}>
</AnyComponent>
)
}
export default getParams
现在在我想要获取参数的组件中,我给了它一个不同的名称。在这种情况下,我将使用您基于类的组件的名称,假设其名称为 Student.jsx
学生.jsx
import React, { Component } from 'react'
import getParams from './getParams'
class Student extends Component {
constructor(props){
super(props)
}
componentDidMount = () => {
//display the id when the component mounts
console.log(this.props.params.id)
}
render = () => {
return (
<div>
Student Id is :{this.props.params.id}
</div>
)
}
}
export default getParams(Student)