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

时间:2020-03-08 23:03:42

标签: reactjs routes

我在Route中设置了参数。它们从我的组件出现在控制台中,但出现“未定义”错误。

<Router>
    <App>
        <Switch>
                <Route exact path='/data/:param' component={data} />
        </Switch>         
    </App>
</Router>

组件

class Data extends Component {
    constructor(props) {
        super(props);

    async componentDidMount() {
        console.log(this.props.match.params.param)

    ...

export default Data;

如果我可以在控制台中看到它们,为什么仍然出现错误?

未处理的拒绝(TypeError):无法读取未定义的属性'params'

enter image description here

1 个答案:

答案 0 :(得分:2)

您需要确保导入的Route是正确的Data

import Data from './Data';
...
     <Route exact path='/data/:param' component={Data} />
...

由于您的组件withRouter已经是Data的子代,因此不需要使用Route高阶组件来包装该组件。

FWIW做

componentDidMount() {
  console.log(this.props.match && this.props.match.params.param);
}

此外,您在执行async时可能不需要componentDidMount()。这也可能是您需要添加上述防御代码的原因。

PS:console.log()可以显示评估的数据,通常在对象eval旁边用i表示。