reactjs - 无法读取未定义的属性 ‘params’ (React Router 4)

标签 reactjs react-router

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

<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={} 时传递 props 似乎工作正常,但在渲染函数中却不行。为什么?

最佳答案

因为使用render,您不会将路由器传递的默认 Prop 传递到组件中,例如匹配、历史记录等。

当你写下这个:

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

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

这样写:

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

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

关于reactjs - 无法读取未定义的属性 ‘params’ (React Router 4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46197178/

相关文章:

javascript - VSCode 自动导入 - 如何强制 Material-UI 全路径导入

node.js - 从 Node HTTP 请求到外部 API 中删除端口号

node.js - 无法将数据推送/更新到现有的 mongo 对象中

reactjs - 如何防止一个组件中的 css 影响 React 中另一个组件中的 css?

css - Material UI - gutterBottom vs paragraph,区别是什么?

javascript - 哪个性能更好 : add and remove event listener on every render VS running an useEffect to update a ref

reactjs - 使用 HashRouter 以编程方式导航

javascript - React Router v4 - 嵌套路由不起作用

javascript - React Router With Handler 显示空白页面

typescript - 带有 typescript 的 React 路由器 v5 上所需的 url 参数,可以是未定义的