TypeError: Cannot read property 'push' of undefined with this.props.history.push

TypeError: Cannot read property 'push' of undefined with this.props.history.push

我正在学习使用 Axios 通过 React 更新项目的课程。我正在按照这些步骤操作,但我遇到了一个函数问题。当我点击更新按钮时,它应该将我重定向到一个预填充了项目表单的页面,但我收到一个错误:TypeError: Cannot read 属性 'push' of undefined

请参阅下面的 handleUpdate 函数问题所在的代码:

export default class ListBooks extends React.Component {
    constructor(props) {
        super(props);
        this.state = { error: null, data: [], number: "", name: "" }
    }
    componentDidMount() {
        Axios.get(process.env.REACT_APP_API_PATH_BOOKS)
            .then(res => {
                this.setState({ data: res.data });
            })
            .catch(errorThrown => {
                this.setState({ error: errorThrown });
            })
    }

    /**
    * Use to delete a book by the number.
    */
    handleDelete = (index) => {
        const id = this.state.data[index].name
        Axios.delete(process.env.REACT_APP_API_PATH_BOOKS + id)
            .then(res => {
                console.log(res);
                console.log(res.data);
                this.setState(prevState => ({ ...prevState, data: prevState.data.filter((book) => book.name !== id) }))
            })
            .catch(errorThrown => {
                this.setState({ error: errorThrown });
            })
    }

    handleUpdate = event => {
        event.preventDefault();
        this.props.history.push(`/admin/${this.state.number}/edit`);
        console.log(this.props);
    }

    render() {
        const { data } = this.state;


        return (
            <div>

                <Container>

                    {data.map((books, index) =>
                        <div key={books.number}>
                            <ListGroup>
                                <ListGroup.Item disabled id={"book-admin" + data[index].number}>{books.number}. {books.name} {books.author}
                                </ListGroup.Item>
                            </ListGroup>
                            <Button variant="outline-warning" size="sm" className="btn-admin-change" onClick={this.handleUpdate}>Modifier</Button>
                            <Button variant="outline-danger" size="sm" className="btn-admin-change" onClick={() => this.handleDelete(index)}>Supprimer</Button>

                        </div>
                    )}
                </Container>

            </div>
        )
    }
}

我以前从未这样使用过 this.props.history,我不太明白它应该如何工作。谁能给我解释一下这里的问题?

如果您使用 React-router Dom 库进行路由,以下步骤会有所帮助..

  • 在此处导入“withRouter”Hoc

即从“react-router”导入 {withRouter};

并用 withRouter(component_name);

包裹你的组件

请参考这个 link https://reactrouter.com/web/api/withRouter

看起来 history props 丢失了,所以通过上述更改应该可以工作