我设置了一个路由来渲染组件:
<Route exact path="/page/:id" location={this.props.location} key={this.props.location.key} render={({ location }) => (
<PageStart key={this.props.location.key} />
)} />
然后在那个组件(PageStart)里面我有:
this.props.match.params.id
但它会抛出一个错误:
Cannot read property 'params' of undefined
简单地调用 component={}
时传递道具似乎可以正常工作,但不能在渲染函数中。为什么?
原文由 Matt Saunders 发布,翻译遵循 CC BY-SA 4.0 许可协议
因为使用
render
你没有将路由器传递的默认道具传递给组件,如匹配、历史记录等。当你写这个:
这意味着在
PageStart
组件中没有props
值。像这样写:
现在
{...props}
会将所有值传递给PageStart
组件。