【发布时间】:2019-08-09 11:45:17
【问题描述】:
我正在从 API 获取数据,我在 console.log(this.state.reviews) 中获取了所有数据,但在地图循环完成后我无法访问数据。
品牌数据是可访问的,唯一的问题是地图循环(评论数组)
我知道它与异步调用有关!我找到了这个Can't access values for Axios calls in map loop 有谁知道如何使用下面的代码来调整它;-)
class App extends React.Component {
constructor(props){
super(props);
this.state = {
reviews : []
};
}
componentDidMount() {
axios.get(`https://api.prime.com/businesses/reviews/${this.props.BrandId}`)
.then((res) => {
const brand = res.data;
this.setState({
// Reviews data
reviews : brand.reviews.items,
// Brand data
logo : brand.business.logo,
name : brand.business.name,
voters : brand.business.voters,
url : brand.business.url
});
})
}
render() {
console.log(this.state.reviews);
return (
<div className="widget-wrapper">
<OwlCarousel className="reviews-container"
loop
nav
margin={12}
dots={false}
items={5}
autoplay={true}
>
{this.state.reviews.map((review) => {
<div key={review.id} className="review-item">
<a href={this.state.url + '/' + review.slug} target="_blank" rel="nofollow">
<div className="review-heading">{review.subject}</div>
<div className="review-content">{review.message}</div>
</a>
</div>
})}
</OwlCarousel>
</div>
)
}
}
【问题讨论】:
-
您需要在
.map箭头函数中使用return,或者将您的.map箭头函数更改为使用(。因为您使用的是this.state.reviews.map((review) => {(带有大括号),所以返回并不像使用(那样隐含。 -
@BrettDeWoody 我已经尝试过了,但我没用,我认为它与异步调用有关
-
您是否遇到任何错误?
-
@BrettDeWoody 我没有收到错误,这和stackoverflow.com/questions/48969613/…是一样的