Reactjs 来自异步方法的呈现数据未定义
我试图从我的MongoDB文档中呈现数据,但我不明白为什么状态是未定义的,而它是一个异步函数,我正在等待它Reactjs 来自异步方法的呈现数据未定义,reactjs,Reactjs,我试图从我的MongoDB文档中呈现数据,但我不明白为什么状态是未定义的,而它是一个异步函数,我正在等待它 export default class App extends React.Component { constructor(props) { super(props); this.state = { offers: null }; this.getOffers = this.getOffe
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
offers: null
};
this.getOffers = this.getOffers.bind(this);
this.renderOffer = this.renderOffer.bind(this);
}
componentDidMount() {
if(!this.state.offers) {
this.getOffers();
}
}
async getOffers() {
let res = await offerService.getAll();
this.setState({ offers: res });
}
renderOffer(product) {
return (
<li key={product._id} className="list__item product">
<h3 className="product__name">{product.title}</h3>
</li>
);
};
render() {
return (
<div className="App">
<Nav />
<ul className="list">
{(this.state.offers && this.state.offers.length > 0) ? (
this.state.offers.map(offer => this.renderOffer(this.state.offer))
) : (
<p>Loading...</p>
)}
</ul>
</div>
);
}
}
导出默认类App扩展React.Component{
建造师(道具){
超级(道具);
此.state={
报价:空
};
this.getOffers=this.getOffers.bind(this);
this.renderofer=this.renderofer.bind(this);
}
componentDidMount(){
如果(!this.state.offers){
这个.getOffers();
}
}
异步getOffers(){
let res=wait offerService.getAll();
this.setState({offers:res});
}
Renderofer(产品){
返回(
{product.title}
);
};
render(){
返回(
{(this.state.offers&&this.state.offers.length>0)(
this.state.offers.map(offer=>this.renderOffer(this.state.offer))
) : (
加载
)}
);
}
}
每当我加载页面时,它都会返回
TypeError:cannotreadproperty'\u id'of undefined
,尽管如果我将res
的输出记录在getOffers()
中,它会显示数据。这是为什么?问题在于您的地图
呼叫:
this.state.offers.map(offer=>this.renderofer(this.state.offer))
您试图使用未定义的变量this.state.offer
而不是offer
map变量。你真正想要的是:
this.state.offers.map(offer=>this.renderOffer(offer))
this.state.offers.map(offer=>this.renderofer(this.state.offer))
可能应该是this.state.offers.map(offer=>this.renderofer(offer))
那么this.state.offer在任何地方都没有定义。你的意思是这个.renderofer(offer
)`?谢谢你,我真是笨手笨脚。成功了@哈姆斯:你应该为这个问题创造一个答案