首页 > 解决方案 > 错误:未捕获 [TypeError:无法读取未定义的属性“id”]

问题描述

我正在使用 react-router-dom 来路由我的组件并对一个路由组件进行测试。我App.js

<Route
     path="/register/:id"
     render={(props) => (
       <Details
         {...props}/>
     )}
></Route>

我试图像这样将匹配添加到组件中

const match = {
        params: {
            id: "123"
        }
    };

Details组件在某些函数中使用,this.props.match.params.id我不知道这些函数是如何调用的,但是我得到了错误

Error: Uncaught [TypeError: Cannot read property 'id' of undefined]

当我使用

console.log(this.props.match)

我明白了

{ match: { params: { id: 'id' } } }

但是当我使用

console.log(this.props.match.params)

我明白了undefined

更新

我认为我传递匹配参数的方式是错误的。在我创建一个 json 对象posts并将该 json 对象传递给这样的测试组件之前

mount(<Details {...posts}/>)

然后我改变方式

mount(<Details {...posts} match={match}>)

它有效。

标签: react-routerjestjs

解决方案


推荐阅读