[英]Use data from async function on React State with JSX
我对 React 和 JS 有点陌生,我在使用从状态上的 ASYNC 返回的数据然后将其作为 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
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)
[Array with Objects]
那么有人可以先解释问题以便我学习,然后共享更新代码的片段会更好。
所有你需要的 - 它只是从服务器获取它后的 setQuote ,在getQuotes
。 并在钩子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
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.