TypeError:无法读取未定义的属性startsWith


import React from 'react';
import AttributeDescription from './AttributeDescription';
class CompEntry extends React.Component{
render(){
let description;
if(this.props.description.startsWith("_")){
description= this.props.description.slice(1, this.props.description.length);
}
if(this.props.description.startsWith("__")){
description = this.props.description.slice(2, this.props.description.length);
}
return(
<div>
<div>
<AttributeDescription description={description}/>
</div>
</div>
);
};
}
export default CompEntry;

如果我在退货前做这些事情,就会出现上述错误。然而,如果我在return之前不做任何事情,只是将this props.description传递到<AttributeDescription/>标记的description prop中,那么一切都很好,定义的props将传递到标记中。如果我尝试访问this.props.description的属性,它似乎不存在。有人知道为什么吗?

这就是我如何使用上面的CompEntry组件:

import React from 'react';
import CompEntry from './CompEntry';
import CompHeading from './CompHeading';
class CompTable extends React.Component{
constructor(props){
super(props);
this.state = {
products: [],
attributes: [],
attDesc: [],
};
this.getEntries = this.getEntries.bind(this);
}
getEntries = async () => {
const response = await fetch('/api/hello/data');
const body = response.json();
return body;
};
componentDidMount(){
this.getEntries()
.then((resolve) => this.setState({
products: resolve.products, 
attributes: resolve.attributes, 
attDesc: resolve.attributesDescription}))
.catch(err=>console.log(err));
};

render(){
console.log(this.state.products);
let highlightEntry= true;
let compEntries = this.state.attributes.map( (item, index) =>{
highlightEntry = !highlightEntry; 
return(
<CompEntry key={index} attribute={item} description={this.state.attDesc[index]} comparees={this.state.products} color={highlightEntry}/>            
);
});
return(
<div id = "comp-table">
<div id="comp-sub-container">   
<CompHeading comparees={this.state.products}/> 
{compEntries}
</div>
</div>  
);
}

}
export default CompTable;

Edit:正如@awarrier99在评论中提到的,response.json()函数返回一个Promise,因此您需要适当地处理它。下面的代码也为此进行了更新。

如果前导字符不是下划线,则不将description设置为任何值。此外,如果它以两个下划线开始,它也以一个下划线开始——这样可以使工作量加倍。我建议这样做:

render(){
let description = this.props.description;
if (description.startsWith("__")) {
description = description.slice(2, description.length);
} else if (description.startsWith("_")) {
description= description.slice(1, description.length);
}
return(
<div>
<div>
<AttributeDescription description={description}/>
</div>
</div>
);
};
}

这样,如果this.props.description没有以任何下划线开头,它仍然会发送该值,并且如果有下划线,slice只会发送一次。通过使用更简单的description变量,而不是在整个过程中重复this.props.description,代码也变得更容易阅读。

更新getEntries函数以返回json()函数给出的Promise。您也可以在上面使用await,但由于getEntriesasync,它已经返回了一个Promise,所以这是最简单的。

getEntries = async () => {
const response = await fetch('/api/hello/data');
return response.json(); // return the Promise
};

相关内容

最新更新