javascript - 无法读取组件中的对象,React
问题描述
我在读取 React 组件中的对象值时遇到问题。我正在尝试读取和写入“recordCount”,但我收到错误消息:
TypeError:无法读取未定义的属性“recordCount”。
知道为什么会抛出错误吗?
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 是未定义的。
您可以将该方法设置为非静态方法,并且该方法应该可以工作。另外,请确保如果您不使用箭头函数,则需要在构造函数中绑定该方法。
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>
);
}
}
使用此代码段而不是您的。
推荐阅读
- jwt - NextAuth 会话访问令牌错误
- verilog - 对于 verilog 上的加法器代码,如何将 1'b1 添加到 4 位向量 [3:0]A?
- python - 如何在 python tkinter 中从 txt 文件创建多个复选框
- python - Python3,jinja2,导入宏时出错
- powershell - 通过 WMI 查询获取帐户状态
- react-native - React Native:标签为1的动画节点不存在
- html - 仅使用 CSS 将容器 div 调整为低于内容总宽度时,图像不会调整大小
- firebase - 在 Flutter 中计算排行榜排名
- julia - 在 Flux 中手动更新层参数
- python - 在 Pandas DataFrame 中将对象转换为浮点数或字符串