【问题标题】:How to solve "TypeError: Cannot read property 'push' of undefined" in react-router?如何解决 react-router 中的“TypeError:无法读取未定义的属性‘push’”?
【发布时间】:2019-05-06 08:58:25
【问题描述】:

1.在文章列表组件中,我将“历史”传递给子组件文章单元组件:

  1. 在子组件(文章单元格)中,我使用history.push,但出现错误。 this.props.history.push(/detail/${this.props.data._id}, {id: this.props.data_id});
   return(
            <div>

                {
                    items.map((item,index) => (
                        <ArticleListCell history={this.props.history} key={index} data={item} tags={tags} />
                    ))
                }



            </div>
 return(
            <div className="ac_container" onClick={
                () => {
                    this.props.history.push(`/detail/${this.props.data._id}`, {id: this.props.data_id});
                    // props.getArticleDetail(props.data_id)
                    // this.props.his
                }
              }
            >
TypeError: Cannot read property 'push' of undefined
onClick
C:/Users/Lee/Documents/Repos/ReactExpressBlog/src/components/ArticleListCell/ArticleListCell.js:18
  15 | return(
  16 |     <div className="ac_container" onClick={
  17 |         () => {
> 18 |             this.props.history.push(`/detail/${this.props.data._id}`, {id: this.props.data_id});
     | ^  19 |             // props.getArticleDetail(props.data_id)
  20 |             // this.props.his
  21 |         }
View compiled、

【问题讨论】:

  • article-List 组件中this.props.history 的值是多少?

标签: javascript reactjs react-native react-router


【解决方案1】:

不需要将历史作为 props 发送给子组件,默认情况下 react-router-dom 提供 withRouter 来获取 history 对象功能组件。 看下面的例子

import React from 'react'
import { withRouter } from 'react-router-dom';
function Test(props) {
    const { match, location, history } = props;
    const handleClick = () => {
        history.push('/home')
    }
    return (
        <div>
            <button onClick={handleClick}>redirect</button>
        </div>
    )
}

export default withRouter(Test);

在此处通过演示代码查看清晰的示例

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 2020-06-20
    • 2021-12-04
    • 2019-07-11
    • 2018-12-21
    相关资源
    最近更新 更多