javascript - 在传递参数时反应未定义的“匹配”
问题描述
有人可以对此有所暗示吗?在这个例子中得到这个函数的评论后
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 结果
解决方案
你这样调用你的函数:
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: {
...
推荐阅读
- angular - 如何使用 NgbModal 仅以角度关闭当前打开的模态?
- exception - 在 Kotlin 异常块中,如何实现“else”(成功)块?
- javascript - 如何让用户输入变量名?
- html - 带有背景图像且没有内容的容器根本不显示
- stanford-nlp - 遍历令牌并找到令牌的实体
- jquery - 更改事件在 Bootstrap 4 日历上不起作用
- windows - 所有 Windows 进程都有关联的命令行,还是只有从 shell 启动的进程?
- mariadb - 如果数据存储在数据库中的 MYSQL 语法
- reactjs - 无法导入显示以下错误的 react-autosuggest 模块
- ios - 覆盖“.formSheet”的 modalPresentationStyle 的水平紧凑环境行为