首页 > 解决方案 > 在传递参数时反应未定义的“匹配”

问题描述

有人可以对此有所暗示吗?在这个例子中得到这个函数的评论后

 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:无法读取未定义的属性“匹配”

指向:

在此处输入图像描述

在这种情况下,即使是日志引用的未定义,我也不知道日志谈论的是哪个未定义。请有人可以澄清为什么反应抱怨未定义?

getComments 的 console.log 结果

在此处输入图像描述

标签: javascriptreactjs

解决方案


你这样调用你的函数:

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

这意味着在您的getComments函数内部,this将引用 props 对象,而不是您的组件。因此,当您调用时this.props.match,您会得到undefined因为this已经是道具的参考。换句话说,它与您调用的相同

`this.props.props.match`

从您的渲染功能内部。显然这会给你 undefined 因为props.props不存在。

为了解决这个问题,最简单的方法是match直接从this. 例如。this.match.params就像this你的 props 对象一样。但是,您的屏幕截图的问题是 props 对象实际上并没有匹配键(您必须弄清楚原因)。

不过,更好的解决方案是将您的匹配详细信息传递给该getComments()函数,因为它看起来有一个非常特定的目的。例如:

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

推荐阅读