无法读取未定义的属性“params"(反应路由器 4) [英] Cannot read property ‘params’ of undefined (React Router 4)

查看:91
本文介绍了无法读取未定义的属性“params"(反应路由器 4)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了一个路由来渲染一个组件:

I have a route set up to render a component:

<Route exact path="/page/:id" location={this.props.location} key={this.props.location.key} render={({ location }) => (
    <PageStart key={this.props.location.key} />
)} />

然后在那个组件(PageStart)里面我有:

Then inside that component (PageStart) I have:

this.props.match.params.id

但它抛出一个错误:

Cannot read property 'params' of undefined

在简单调用 component={} 时传递 props 似乎工作正常,但在渲染函数中不起作用.为什么?

Passing props when simply calling component={} seems to work fine but not in a render function. Why?

推荐答案

因为使用 render 你没有将路由器传递的默认道具传递给组件,如匹配、历史等.

Because with render you are not passing the default props passed by the router into component, like match, history etc.

当你写这个时:

<PageStart key={this.props.location.key} />

这意味着 PageStart 组件中没有 props 值.

It means no props value in PageStart component.

这样写:

render = {props => <PageStart {...props} key={this.props.location.key} /> } />

现在 {...props} 会将所有值传递给 PageStart 组件.

Now {...props} will pass all the value into PageStart component.

这篇关于无法读取未定义的属性“params"(反应路由器 4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆