Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 从react中的路由末尾获取实体指示符id的正确方法?_Reactjs - Fatal编程技术网

Reactjs 从react中的路由末尾获取实体指示符id的正确方法?

Reactjs 从react中的路由末尾获取实体指示符id的正确方法?,reactjs,Reactjs,我编写了一些代码,从React组件中的路由末尾获取实体指示符id: const pathname = this.props.location.pathname; const lastPathPart = pathname.split('/').slice(-1)[0]; const requestedJobId = Number(lastPathPart); 上面的代码根据需要/预期从路由的末尾获取请求的作业id,但是在React中是否有更合适或结构化的方法来执行此操作?1。如果它是一个功能组

我编写了一些代码,从React组件中的路由末尾获取实体指示符id:

const pathname = this.props.location.pathname;
const lastPathPart = pathname.split('/').slice(-1)[0];
const requestedJobId = Number(lastPathPart);

上面的代码根据需要/预期从路由的末尾获取请求的作业id,但是在React中是否有更合适或结构化的方法来执行此操作?

1。如果它是一个功能组件,您可以使用React router的
useParams
钩子

示例:

假设这是你的路线

<Router>
   <Switch>
      <Route path="/:id" children={<User />} />
   </Switch>
</Router>

2。如果它是一个类组件,您可以参考。

您要通过什么路径到达
路线
?这个
pathname
看起来怎么样。您使用的是组件类还是挂钩?我的应用程序使用的是类(不是挂钩)。路线如下所示:
import { useParams } from "react-router";

function User() {
  let { id } = useParams();
  return <h2>User {id}</h2>;
}