【发布时间】:2021-05-25 20:11:34
【问题描述】:
我一直在尝试构建一个随机报价应用程序。到目前为止,我有这个:https://codesandbox.io/s/nice-heyrovsky-4msq4?file=/src/App.js
简而言之,我从 API 中获取引用列表,然后尝试在页面加载时以及每次按下按钮时显示引用和作者。但是有一个问题。
export default function App() {
useEffect(() => {
fetch(
"https://gist.githubusercontent.com/natebass/b0a548425a73bdf8ea5c618149fe1fce/raw/f4231cd5961f026264bb6bb3a6c41671b044f1f4/quotes.json"
)
.then((data) => data.json())
.then((quotes) => setAllQuotes(quotes));
}, []);
const [allQuotes, setAllQuotes] = useState([]);
// this is the array of all quote objects
const [quoteIndex, setQuoteIndex] = useState(0);
//this is the number used as array index
const [text, setText] = useState("This app is Broken");
// this is the quote text to be displayed
const [author, setAuthor] = useState("Press set twice");
// this is the quote author to be displayed
const [chosenQuote, setChosenQuote] = useState({});
// this is the selected quote object
function randomNumber() {
return Math.floor(Math.random() * allQuotes.length);
}
let handleClick = () => {
setQuoteIndex(randomNumber);
setText(chosenQuote.quote);
setAuthor(chosenQuote.author);
setChosenQuote(allQuotes[quoteIndex]);
// this is supposed to choose a random object within the array, and set text and quote state to the quote and author properties of the selected object
};
console.log(chosenQuote);
return (
<div id="quote-container">
<div id="quote-box">
<h1 id="text">{text}</h1>
<p id="author">{author}</p>
{/*when I press the button, it loads the next quote, but displays the previous quote, hence why nothing displays on first click */}
<button onClick={handleClick}>New Quote</button>
</div>
</div>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
如果我在页面加载时尝试加载引号,则会出现“无法读取未定义的属性(引号)”错误。如果我尝试在页面加载后通过编辑 javascript 加载引号,那么它可以工作,但它会显示来自先前加载的对象的消息,而不是当前的。您可以在代码沙箱中看到行为。
那么,有人可以向我解释为什么会发生这种情况以及如何解决它,以便应用在加载时正确显示引号,然后在点击时更改?
【问题讨论】:
标签: javascript reactjs api react-hooks