gpt4 book ai didi

javascript - React Js Uncaught( promise )TypeError : Cannot read property of undefined

转载 作者:行者123 更新时间:2023-11-29 10:59:22 29 4
gpt4 key购买 nike

我正在学习使用react,在发出 ajax 请求时面对这个问题,即使我得到了响应,但无法将该响应传递给其他函数 { this.showBattersData(data);我可以在哪里渲染 dom。很明显我在这里遗漏了一些东西。任何帮助将不胜感激。

import React, {Component} from 'react'
import { fetchFactory } from '../Fetch/fetchFactory'

var batters = [];
var rowdata = "";


export class Body extends React.Component {
constructor(props) {
super(props);
this.battersDataFetchReq = this.battersDataFetchReq.bind(this);
this.showBattersData = this.showBattersData.bind(this);
this.battersDataFetchReq();
}

//ajax request
battersDataFetchReq() {
fetchFactory('./assets/some.json', 'GET')
.then(function(data) {
//this.showBattersData = this.showBattersData.bind(this);
this.showBattersData(data); // this is where i'm getting this error

})
}

showBattersData(res) {
console.log("inside showBattersData:: ", res);
rowdata = `
<table id="batters" name="batters" class="table table-bordered table-hover">
<caption>List of batters</caption>
<th>#</th>
<th>Id</th>
<th>Type</th>
<tbody id="batters_body">`;
batters = res.batters.batter;
for(var i = 0; i < batters.length; i++) {
rowdata += `
<tr>
<td>${[i + 1]}</td>
<td>${batters[i].id}</td>
<td>${batters[i].type}</td>
</tr>`;
}
rowdata += `</tbody></table>`;
}


render() {
return (
<div>
{rowdata}
</div>
);
}
}

最佳答案

您的问题与JavaScript 中的Context 概念有关。

在 JS function 中有它们的上下文,这意味着 this 关键字引用函数本身。

您可以使用以下两种解决方案之一:

一:

battersDataFetchReq() {
let self = this;

fetchFactory('./assets/some.json', 'GET')
.then(function (data) {
self.showBattersData(data);
})
}

Tow(又名箭头函数):推荐的解决方案

battersDataFetchReq() {
fetchFactory('./assets/some.json', 'GET')
.then((data) => {
this.showBattersData(data);
})
}

想知道为什么吗?来自 MDN:

An arrow function expression has a shorter syntax than a function expression and does not have its own this.

继续阅读...(两个链接均来自 MDN )

关于javascript - React Js Uncaught( promise )TypeError : Cannot read property of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50284784/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com