簡體   English   中英

通過參數反應未定義的“匹配”

[英]React 'match' of undefined on pass a params

有人可以對此有所保留嗎? 在這個例子中得到此功能的評論后

 getComments() {
        fetch("/posts/" + this.props.match.params.id + "/comments", {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",

            }
        })
            .then(response => {
                return response.json();
            })

            .catch(err => {
                console.log(err);
            });
    }

加載功能

 load() {
        return this.props.getComments().then(comments => {
            this.setState({ comments });

            return comments;
        });
    }

在反應日志中顯示:

TypeError:無法讀取未定義的屬性“ match”

往:

在此處輸入圖片說明

因為在這種情況下,甚至日志引用的未定義我也不知道日志所談論的是哪個未定義。 請有人可以闡明為什么反應抱怨不確定的?

getComments的console.log結果

在此處輸入圖片說明

您正在這樣調用函數:

return this.props.getComments().then(comments => {

這意味着在getComments函數內部, this將引用props對象,而不是您的組件。 因此,當您調用this.props.match ,您將變得undefined因為this已經是props的引用。 換句話說,它與您呼叫

`this.props.props.match`

從渲染函數內部。 顯然,這將給您未定義的信息,因為props.props不存在。

為了解決這個問題,最簡單的方法是直接從this訪問match 例如。 this.match.params因為this已經是您的props對象。 但是,屏幕截圖的問題在於props對象實際上沒有匹配鍵(您必須找出原因)。

不過,更好的解決方案是將您的比賽詳細信息傳遞給getComments()函數,因為它看起來有非常特定的用途。 例如:

function getComments(id) {
  fetch(`/posts/${id}/comments`, {
    method: 'GET',
    headers: {
...

暫無
暫無

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

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