如何在第一次重新渲染时及时更新React状态



在下面的代码中,我从API获取字典数据,对该数据进行排序和过滤,然后在屏幕上显示一个随机单词。这段代码是可以工作的,但是正如您所看到的,我使用了一种简单的方法,即最初基于一个常规变量设置当前单词,然后每次都基于一个状态变量设置它。

这是因为当我试图使用状态,第一次重新渲染按钮点击产生了一个错误,currentPage是未定义的,这个词没有显示,但它以后每次工作。

我有一种感觉,这与useState的异步特性和相对于渲染的状态变化的时间有关。你会看到注释,我试图使用useEffect,但这也不起作用。如果有人能给我指出正确的方向,一定有更干净的方法!

import React, { useState, useEffect } from "react";
import Word from "./components/Word";
const options = {
method: "GET",
headers: {
"X-RapidAPI-Key": "fd76888365mshc55b027be74dc4dp1d4f7ejsn88ecdcc39f3f",
"X-RapidAPI-Host": "lexicala1.p.rapidapi.com",
},
};
const App = () => {
const [entryCount, setEntryCount] = useState(0);
const [pageCount, setPageCount] = useState(1);
const [currentPage, setCurrentPage] = useState("");
const [currentWord, setCurrentWord] = useState("");
// useEffect(() => {
//   const word = document.querySelector('.word')
//   word.textContent = currentWord;
// });
const shuffleResults = (array) => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
};
const filterResults = (words) => {
words = words.results;
const validPOS = ["noun", "verb", "adjective", "adverb"];
words = words.filter((word) => validPOS.includes(word.headword.pos));
return words;
};
const getDictionary = async () => {
const response = await fetch(
`https://lexicala1.p.rapidapi.com/search-entries?source=global&language=sv&page=${pageCount}&page-length=30&sample=30&text=`,
options
);
let wordsData = await response.json();
wordsData = filterResults(wordsData);
wordsData = shuffleResults(wordsData);
setCurrentPage(wordsData);
return wordsData;
};
let page = "";
const generateWord = async () => {
if (!currentPage) {
page = await getDictionary();
setCurrentWord(page[entryCount].headword.text);
} else setCurrentWord(currentPage[entryCount].headword.text);
if (entryCount === currentPage.length - 1) {
setPageCount(pageCount + 1);
setEntryCount(0);
setCurrentPage("");
} else setEntryCount(entryCount + 1);
};
return (
<div className="App">
<button
onClick={async () => {
await generateWord();
}}
>
hey
</button>
<Word word={currentWord} />
<div className="word"></div>
</div>
);
};
export default App;

你可以像这样更新你的useEffect

import { useFocusEffect} from "@react-navigation/native";
const isFocused = useIsFocused();
useEffect(()=>{
setCurrentPage(0)
},[isFocused])

最新更新