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

时间:2018-08-10 06:25:35

标签: reactjs react-router

我是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);

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

4 个答案:

答案 0 :(得分:1)

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

<BrowserRouter>
        <Switch>
            <Route path="/Feedback">
        <Switch>
<BrowserRouter>
在上述路由定义中,

的“反馈”组件中的match对象不为null,但是如果我们在反馈中包含其他组件并尝试访问它,那就是错误。

答案 1 :(得分:0)

当您要使用组件时,不需要像代码那样的功能,就可以像这样更改它:

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

或使用渲染功能(如果您想要这样的功能

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

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

答案 2 :(得分:0)

https://stackoverflow.com/a/57628327/12378703 这很完美...尝试一下

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

答案 3 :(得分:0)

这解决了我的问题:

<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);
    }
}
相关问题