簡體   English   中英

類型錯誤:無法使用 this.props.history.push 讀取未定義的屬性“推送”

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

我正在學習使用 Axios 使用 React 更新項目的課程。我正在執行這些步驟,但我遇到了 function 的問題。當我單擊更新按鈕時,它應該將我重定向到一個預填充了項目表單的頁面但我收到一個錯誤:TypeError: Cannot read property 'push' of undefined

請參閱下面的 handleUpdate function 問題所在的代碼:

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); 包裹你的組件

請參考此鏈接https://reactrouter.com/web/api/withRouter

看起來 history props 丟失了所以通過上面的更改這應該可以工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM