我正在基于 WP API 构建一个 SPA,希望渲染文章和它们的特色图片,但它们在不同的端点上。
在渲染时,React 不会等待请求解决,并出现错误:"Uncaught Invariant Violation: Objects are not valid as a React child (found: [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;
getImg()
方法返回一个节点 (<img src={obj.url} />
),但你正在从 img 的src
属性中调用它 (<img src={this.getImg()} />
)。最好将 obj.url 设置为状态,并且仅在其具有值时才呈现它。 - sallf{this.getImg()}
也会出现相同的错误。 - Dico Didiraja