Reactjs 如何在React上呈现异步内容?

Reactjs 如何在React上呈现异步内容?,reactjs,asynchronous,promise,async-await,Reactjs,Asynchronous,Promise,Async Await,我正在构建一个基于wpapi的SPA,我想同时呈现帖子和它们的特色图片,但它们有不同的端点 渲染时,React不要等待请求解决并获取错误:“未捕获不变冲突:对象作为React子对象无效(找到:[object Promise]) 完全是Promise和Async/Await函数的初学者。我甚至不知道我是否正确使用了它 import React, { Suspense, Component } from "react"; import { FontSizes, FontWeights, Primar

我正在构建一个基于wpapi的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;
import React,{suspent,Component}来自“React”;
从“office ui fabric react”导入{FontSizes、FontWeights、PrimaryButton、DefaultButton};
从“axios”导入axios;
导入“./Home.styl”
类Home扩展组件{
构造函数(){
超级();
此.state={
员额:[]
}
}
组件willmount(){
这个.renderPosts();
}
renderPosts(){
axios.get()https://cors-anywhere.herokuapp.com/https://sextou.didiraja.net/wp-json/wp/v2/posts')
。然后((响应)=>{
//console.log(响应)
这是我的国家({
帖子:response.data,
})
})
.catch((错误)=>console.log(错误))
}
异步getImg(mediaId){
常量getImg=axios
.get('https://cors-anywhere.herokuapp.com/https://sextou.didiraja.net/wp-json/wp/v2/media/17')
。然后((响应)=>{
返回{
url:response.data.source\u url,
alt:response.data.alt_text,
}
})
const obj=getImg
返回(
)
}
render(){
const{posts}=this.state
返回(
塞克斯图!
{
posts.map((post,key)=>{
返回(
{post.title.rendered}
{post.acf.event_date}
{post.extract.rendered}
)
})
} 
);
}
}
导出默认主页;

您可以使用与获取帖子相同的方式获取图像:

将它们包括在您的
状态中

this.state = {
  posts: [],
  image: null
};
调用
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


这里有一个。

在检索帖子之前,您需要处理渲染。您的
getImg()
方法返回一个节点(
),但您是从img
src
)调用它的。最好只是将obj.url设置为state,并仅当它有值时才呈现它。@sallf我粘贴了错误的调用,即使在我尝试调用
{this.getImg()}
时也会出现相同的错误。我的最终意图是使用post中的id动态图像,但根据我粘贴的代码,这解决了问题。它帮助我找到了我的解决方案,所以我检查为解决!谢谢,伊斯特万:)