gpt4 book ai didi

javascript - 通过 JSX 在 React State 上使用来自异步函数的数据

转载 作者:行者123 更新时间:2023-12-04 07:22:10 24 4
gpt4 key购买 nike

我对 React 和 JS 有点陌生,我在使用从 ASYNC on State 返回的数据然后将其作为 JSX 传递时遇到问题。这是我的代码:
(PS:当我从内部函数控制台日志时,我从数据库接收数据及其正常工作,但我似乎无法找到在外部使用它的方法)

import {useState, useEffect} from 'react';
import {supabase} from '../db/supabase'
import styled from 'styled-components';
//CSS
const Container = styled.div`
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;`

const RandomQuote = styled.h1`
width: 75%;
font-size: 3.65em;
color: #333;`
export default function App() {
const [quote, setQuote] = useState();

useEffect(() => {
getQuotes().then().catch();
});

async function getQuotes() {
const {data, error} = await supabase
.from('quotes_en')
.select('quote')
const getRandomQuote = await data[Math.floor(Math.random() * data.length)];
if (error) console.table(error)
setQuote(getRandomQuote);
};

return (
<Container>
<RandomQuote>{quote}</RandomQuote>
</Container>
);
}
所以 random_quote 返回: Object quote: "Our life will pass like the traces of a cloud, it will be scattered like mist that is chased by the rays of the sun. For our time is the passing of a shadow. Our lives will run like sparks through the stubble." __proto__: Object使用 console.log [对象]
数据返回时: Array(4) 0: {quote: "Sometimes it takes sadness to know happiness, nois…ppreciate silence, and absence to value presence."} 1: {quote: "If there is no enemy within, the enemy outside can make us no harm."} 2: {quote: "Our life will pass like the traces of a cloud, it …r lives will run like sparks through the stubble."} 3: {quote: "Little by little, day by day, what is meant for you will find its way"} length: 4 __proto__: Array(0) [带对象的数组]
所以有人可以先解释这个问题以便我学习,然后分享一段更新的代码会更好。

最佳答案

所有你需要的——它只是从服务器获取它后的 setQuote,在 getQuotes 内部.并在 Hook useEffect 中使用此功能第一次渲染。
像这样:

    const [quote, setQuote] = useState();

const getQuotes = async() => {
const {data, error} = await supabase
.from('quotes_en')
.select('quote')
const getRandomQuote = await data[Math.floor(Math.random() * data.length)];
if (error) console.table(error)
setQuote(getRandomQuote); //Here quote goes to state
};

useEffect(() => {
getQuotes().then().catch() //nasty hack for IDE
}, []);

关于javascript - 通过 JSX 在 React State 上使用来自异步函数的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68426239/

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