我正在基于WP API构建SPA,并且希望同时渲染帖子及其特色图片,但是它们位于单独的端点中。
渲染时,React不要等待请求解决并得到错误:“未捕获的不变违规:对象作为React子对象无效(找到:[object Promise])。”
完全是有关Promise和Async / Await功能的初学者。甚至不知道我是否使用正确。
import React, { Suspense, Component } from "react";
import { FontSizes, FontWeights, PrimaryButton, DefaultButton } from 'office-ui-fabric-react';
import axios from "axios";
import './Home.styl'
class Home extends Component {
constructor() {
super();
this.state = {
posts: []
}
}
componentWillMount() {
this.renderPosts();
}
renderPosts() {
axios.get('https://cors-anywhere.herokuapp.com/https://sextou.didiraja.net/wp-json/wp/v2/posts')
.then((response) => {
// console.log(response)
this.setState({
posts: response.data,
})
})
.catch((error) => console.log(error))
}
async getImg(mediaId) {
const getImg = axios
.get('https://cors-anywhere.herokuapp.com/https://sextou.didiraja.net/wp-json/wp/v2/media/17')
.then((response) => {
return {
url: response.data.source_url,
alt: response.data.alt_text,
}
})
const obj = getImg
return (
<img src={obj.url} />
)
}
render() {
const { posts } = this.state
return (
<span className="Home-route">
<h1 style={{textAlign: 'center'}}>Sextou!</h1>
<div className="events-wrapper">
{
posts.map((post, key) => {
return (
<div className="event-card" key={key}>
<img src={this.getImg()} />
<h2
className="event-title"
style={{ fontSize: FontSizes.size42, fontWeight: FontWeights.semibold }}
>
{post.title.rendered}
</h2>
{post.acf.event_date}
<span>{post.excerpt.rendered}</span>
<a href={post.acf.event_link} target="_blank">
<DefaultButton
text="Acesse o evento"
/>
</a>
<a href={post.acf.event_ticket} target="_blank">
<PrimaryButton
text="Comprar ingressos"
/>
</a>
</div>
)
})
}
</div>
</span>
);
}
}
export default Home;
答案 0 :(得分:1)
您可以使用与获取帖子相同的方式获取图像:
将它们包括在您的state
this.state = {
posts: [],
image: null
};
在getImage
中致电componentWillMount
componentWillMount() {
this.getPosts();
this.getImage();
}
setState
,当承诺解决时:
.then(response => {
this.setState(state => ({
...state,
image: {
url: response.data.source_url,
alt: response.data.alt_text
}
}));
});
显示加载屏幕或微调框,直到图像加载
render() {
const { posts, image } = this.state;
if (!image) {
return "Loading";
}
// ...
}
我也建议您使用componentDidMount
而不是componentWillMount
,因为componentWillMount
is deprecated and is considered unsafe.