React Router v4 - 无法读取未定义的属性'params'



我是 React 的初学者。我只需要在加载页面时从 URL 获取路径参数。我的网址如下。

http://localhost:3000/explorer/test/111

我已经设置了如下路线,

<Route
exact path="/explorer/test/:id"
component={() => <BlockPage />}
/>

然后在<BlockPage />组件中,我需要在加载组件时获取:id的值。因此,我添加了以下代码段来获取 id,但它给了我标题中的错误。

import React, { Component } from 'react';
import NavigationComp from './Navigation';
import { withRouter } from 'react-router-dom';
const BlockPage = () =>
<div>
<NavigationComp/>
<BlockData />
</div>
class BlockData extends Component {
componentDidMount() {
console.log(this.props.match.params.id);
}
render(){
return(.....)
}
}
export default withRouter(BlockPage);

我犯了什么错误?有人可以向我解释一下吗?我的目标是将 111 值从 URL 获取到componentDidMount()

当你想使用组件时,你不需要像你的代码那样的功能,你可以像它一样改变它:

<Route
exact path="/explorer/test/:id"
component={<BlockPage />}
/>

或者如果你想要这样的函数,请使用渲染函数

<Route
exact path="/explorer/test/:id"
render={(props) => <BlockPage {...props} />}
/>

然后在this.props.match.params中,您可以访问您的ID。

发生这种情况是因为该组件是ReactRouter知道的其他组件的子组件。例如

<BrowserRouter>
<Switch>
<Route path="/Feedback">
<Switch>
<BrowserRouter>

在上面的路由定义中,反馈组件中的 match 对象不为 null,但如果反馈中有其他组件并尝试访问它,那就是错误。

https://stackoverflow.com/a/57628327/12378703 这非常有效...试试这个

<Route
exact path="/explorer/test/:id"
render={(props) => <BlockPage {...props} />}
/>

这解决了我的问题:

<CPAroute exact path="/advcampaigns/:id" component={AdvCampaigns}/>
class AdvCampaigns extends React.Component {
constructor(props) {
super(props);
this.state = {
activePage: 1
};
};
componentDidMount() {
console.log(this.props.**computedMatch**.params.id);
}
}

我也遇到了同样的问题。 尝试了上述所有解决方案,但没有奏效。 然后我只是控制台登录this.props

const productName = this.props.params.<YOUR_DYNAMIC_URL>;

没有匹配在此.道具

它奏效了,不知道是怎么回事,但它奏效了。 可能对其他人有帮助。

最新更新