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

3

我正在基于 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;

在文章被检索出来之前,您需要处理渲染。 - Dave Newton
你的 getImg() 方法返回一个节点 (<img src={obj.url} />),但你正在从 img 的 src 属性中调用它 (<img src={this.getImg()} />)。最好将 obj.url 设置为状态,并且仅在其具有值时才呈现它。 - sallf
@sallf,我贴错了调用,即使我尝试调用{this.getImg()}也会出现相同的错误。 - Dico Didiraja
1个回答

4
你可以像获取帖子一样获取图片:
将它们包含在你的state中。
this.state = {
  posts: [],
  image: null
};

componentWillMount中调用getImage

componentWillMount() {
  this.getPosts();
  this.getImage();
}

当 Promise 完成后,调用 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已被弃用且被认为是不安全的。

这里是一个codesandbox示例


我的最终目的是使用帖子ID创建动态图像,但根据我贴出的代码,这解决了问题。它帮助我找到了解决方案,所以我标记为已解决!谢谢Istvan :) - Dico Didiraja

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接