gpt4 book ai didi

javascript - 在 react 组件挂载之前加载 cms 内容

转载 作者:行者123 更新时间:2023-11-30 19:11:11 25 4
gpt4 key购买 nike

我想将我的帖子从 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都会出现。如何仅在定义帖子后才呈现元素?

最佳答案

您始终可以在渲染之前进行检查并渲染后备加载指示器..

return (
post ?
<div className={"section"}>
<div className={"container"}>
<div className={"first-post"}>
<div className={"first-post-title"}>
<h2>
{post.title.length > 20
? post.title.slice(0, 85) + " ..."
: post.title}
</h2>
</div>
</div>
</div>
</div>
: "loading..."
)

以上代码仅在定义后才加载帖子,否则返回“正在加载”。

useEffect Hook 中,您可以调用 API 并设置状态。

  useEffect(() => {
fetch("URL")
.then(response => response.json())
.then(json => setPost(json));
}, [])

API 调用完成后,状态会发生变化,组件会使用发布数据重新呈现。

一个例子 https://stackblitz.com/edit/react-htofev

关于javascript - 在 react 组件挂载之前加载 cms 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58459740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com