反应.当浏览器启动时,我试图将引号的默认状态设置为包含引号数组中一个随机对象的数组



我正试图将quote的默认值设置为luanch上报价列表中的随机报价。目前在luanch上,我们检索数据并将其设置为引号。在我们点击按钮之前,我们的窗口没有显示报价。我想为报价设置一个defalt值,这样当我们启动时,我会显示一个随机报价。

import React from 'react'
import { useEffect, useState } from 'react'
const QuoteGenerator = () => {
//Initializing quote and quotes
const [quotes, setQuotes] = useState([])
const [quote, setQuote] = useState([])
//Fetching our quote list
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => setQuotes([...data]))
}, [])
//This function is used to update the current quote displayed to a new quote when our button 
//is clicked
const setNewQuote = () => {
const index = Math.floor(Math.random() * 100)
return setQuote(quotes.slice(index, index + 1 ))
}
//On launch quoteEntry is an empty array.
//I want to set the default state of quote to a random array from quotes containing one 
//object.
const quoteEntry = quote.map(item => (
<div key={item.id}>
<h3>{item.title}</h3>
</div>
))
return (
//What you see in browser
<div>
<h1>Your Quote</h1>
<br />
<div>
<h5>{quoteEntry}</h5>
</div>
<br />
<button onClick={setNewQuote}>New quote</button>
</div>
)
}
export default QuoteGenerator

您可以尝试类似的

import React from 'react'
import { useEffect, useState } from 'react'
const QuoteGenerator = () => {
//Initializing quote and quotes
const [quotes, setQuotes] = useState([]);
const [quote, setQuote] = useState([]);
//Fetching our quote list
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then((res) => res.json())
.then((data) => {
setQuotes([...data]);
const index = Math.floor(Math.random() * 100);
setQuote([...data.slice(index, index + 1)]);
});
}, []);

//This function is used to update the current quote displayed to a new quote when our button
//is clicked
const setNewQuote = () => {
const index = Math.floor(Math.random() * 100);
setQuote(quotes.slice(index, index + 1));
};
//On launch quoteEntry is an empty array.
//I want to set the default state of quote to a random array from quotes containing one
//object.
function quoteEntry() {
return quote.map((item) => (
<div key={item.id}>
<h3>{item.title}</h3>
</div>
));
}
return (
//What you see in browser
<div>
<h1>Your Quote</h1>
<br />
<div>
<h5>{quoteEntry()}</h5>
</div>
<br />
<button onClick={setNewQuote}>New quote</button>
</div>
);
};

export default QuoteGenerator

最新更新