gpt4 book ai didi

javascript - 如何解决react-router中的 "TypeError: Cannot read property ' push' of undefined“?

转载 作者:行者123 更新时间:2023-12-02 23:42:38 31 4
gpt4 key购买 nike

1.在article-List组件中,我将“history”传递给子组件article-cell组件:

  • 在子组件(article-cell)中,我使用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、

    最佳答案

    无需将历史记录作为 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);

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

    Code sample

    关于javascript - 如何解决react-router中的 "TypeError: Cannot read property ' push' of undefined“?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56001865/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com