在反应组件安装之前加载 cms 内容

我想将我的帖子从 ButterCMS 导入 React,但我不知道如何处理异步问题。


import React, { useState } from "react"

import Butter from "buttercms"


import gradient from "../../images/TealLove.jpg"


export default () => {

  const butter = Butter("API_KEY")

  const [post, setPost] = useState()


  butter.post.list({ page: 1, page_size: 10 }).then(function(response) {

    setPost(response.data.data[0])

  })


  return (

    <>

      <div className={"section"}>

        <div className={"container"}>

          <div className={"first-post"}>

            <figure className={"image"}>

              <img src={gradient} alt=""></img>

            </figure>


            <div className={"first-post-title"}>

              <h2>

                {post.title.length > 20

                  ? post.title.slice(0, 85) + " ..."

                  : post.title}

              </h2>

            </div>

          </div>

        </div>

      </div>

    </>

  )

}

每次我运行这个,错误post is undefined都会出现。如何仅在定义帖子后才呈现元素?


慕容森
浏览 118回答 1
1回答

德玛西亚99

您始终可以在渲染之前进行检查并渲染后备加载指示器..return (&nbsp; &nbsp; post ?&nbsp; &nbsp; &nbsp; <div className={"section"}>&nbsp; &nbsp; &nbsp; &nbsp; <div className={"container"}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div className={"first-post"}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div className={"first-post-title"}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <h2>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {post.title.length > 20&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ? post.title.slice(0, 85) + " ..."&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : post.title}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </h2>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; </div>&nbsp; : "loading..."&nbsp; )上面的代码仅在定义后才加载 post,否则返回“loading”。在useEffect钩子内部,您可以调用 API 并设置状态。&nbsp; useEffect(() => {&nbsp; &nbsp; &nbsp; fetch("URL")&nbsp; &nbsp; &nbsp; &nbsp; .then(response => response.json())&nbsp; &nbsp; &nbsp; &nbsp; .then(json => setPost(json));&nbsp; }, [])API 调用完成后,状态会发生变化,并且组件会使用发布数据重新呈现。一个例子https://stackblitz.com/edit/react-htofev
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript