gpt4 book ai didi

javascript - 无法读取组件、React 中的对象

转载 作者:行者123 更新时间:2023-12-01 00:18:16 25 4
gpt4 key购买 nike

我在读取 React 组件中的对象值时遇到问题。我正在尝试读取和写入“recordCount”,但收到错误消息:

TypeError: Cannot read property 'recordCount' of undefined.

知道为什么会抛出错误吗?

import React, { Component } from 'react';

export class UrunlerComponentList extends Component {
displayName = UrunlerComponentList.name

constructor(props) {
super(props);
this.state = { urunler_: [], recordCount: 0, loading: true };


}

componentDidMount() {
fetch('http://localhost:55992/api/search/arama?q=&PageIndex=1')
.then(response => response.json())
.then(data => {
this.setState({ urunler_: data.products, recordCount: data.RecordCount, loading: false });
});
}

static renderUrunlerTable(urunler_) {
return (
<div>
<header className="mb-3">
<div className="form-inline">
<strong className="mr-md-auto"> {recordCount} Items found </strong>
</div>
</header>

{
urunler_.map(urun =>
<article className="card card-product-list">
...............................
...............................
...............................
</article>
)}
</div>


);
}

render() {
let contents = this.state.loading
? <p><em>Loading...</em></p>
: UrunlerComponentList.renderUrunlerTable(this.state.urunler_);

return (
<div>
{contents}
</div>
);
}
}

最佳答案

由于您使用的是静态方法,因此 this 不会引用组件,因此 this.state 未定义。

您可以将该方法设为非静态,并且该方法应该可以工作。另外,请确保如果您不使用箭头函数,则需要在构造函数中绑定(bind)该方法。

import React, { Component } from 'react';

export class UrunlerComponentList extends Component {
displayName = UrunlerComponentList.name

constructor(props) {
super(props);
this.state = { urunler_: [], recordCount: 0, loading: true };
this.renderUrunlerTable = this.renderUrunlerTable.bind(this);

}

componentDidMount() {
fetch('http://localhost:55992/api/search/arama?q=&PageIndex=1')
.then(response => response.json())
.then(data => {
this.setState({ urunler_: data.products, recordCount: data.RecordCount, loading: false });
});
}

renderUrunlerTable(urunler_) {
return (
<div>
<header className="mb-3">
<div className="form-inline">
<strong className="mr-md-auto"> {this.state.recordCount} Items found </strong>
</div>
</header>

{
urunler_.map(urun =>
<article className="card card-product-list">
...............................
...............................
...............................
</article>
)}
</div>


);
}

render() {
let contents = this.state.loading
? <p><em>Loading...</em></p>
: this.renderUrunlerTable(this.state.urunler_);

return (
<div>
{contents}
</div>
);
}
}

使用此代码片段而不是您的代码片段。

关于javascript - 无法读取组件、React 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59618628/

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