[英]useState no rerendering
有人可以幫我弄清楚當我使用ReactHooks改變狀態時會怎么回事嗎?
const [newsCatalog, setNewsCatalog] = useState([]);
useEffect(() => {
fetchNews();
});
const fetchNews = async () => {
const GetAllNewArticleResults = await GetAllNewArticle();
let promises = [];
let tempNewsCatalog = newsCatalog;
GetAllNewArticleResults.map(async e => {
promises.push(
await htmlToJson.parse(
e.HTMLNewsCode,
{
title: function($doc) {
return textTruncate($doc.find("H2").text(), 50);
},
link: function($doc) {
return $doc.find("A").attr("href");
},
content: function($doc) {
return textTruncate($doc.find("P").text(), 80);
},
imageURL: function($doc) {
return $doc.find("img").attr("src");
}
},
function(err, result) {
tempNewsCatalog.push({
...result
});
}
)
);
return null;
});
Promise.all(promises).then(() => {
setNewsCatalog(newsCatalog, ...tempNewsCatalog);
});
};
return (
<div className="container mb-4" id="News">
<div className="h4 mb-3">OUR NEWS</div>
<div className="d-flex justify-content-between flex-wrap mw-90">
{newsCatalog.length}
</div>
</div>
);
當我嘗試運行它時,它將在“ newsCatalog.length”中顯示“ 0”。 但是當我嘗試檢查它時,上面已經有物品了。
// helper method
function htmlToJson(htmlNewsCode) {
return new Promise((resolve, reject) => {
htmlToJson.parse(
htmlNewsCode,
{
title: function($doc) { return textTruncate($doc.find("H2").text(), 50); },
// implement your other methods
},
(err, result) => {
if (err) {
reject(err);
return;
}
resolve(result)
}
)
})
}
// your component
const [newsCatalog, setNewsCatalog] = React.useState([]);
React.useEffect(() => {
async function fetchNews() {
// TODO: Implement error handling using try/catch
const GetAllNewArticleResults = await GetAllNewArticle();
const promises = GetAllNewArticleResults.map((e) => {
return htmlToJson(e. HTMLNewsCode);
})
const results = await Promise.all(promises);
setNewsCatalog(prev => [...prev, ...results]);
}
fetchNews();
}, /* You probably need to specify the DEPS */)
您的Promise.all
調用可能失敗了,並且此代碼存在問題
tempNewsCatalog.push({
...result
});
它正在推向newsCatalog
。 因為它是對象,並通過指針與tempNewsCatalog
連接。 因此,您有價值觀,但沒有回報。
嘗試創建epmty數組,然后將其推送到此處
感謝AngelSalazar我嘗試更改代碼
const [newsCatalog, setNewsCatalog] = useState([]);
React.useEffect(() => {
async function fetchNews() {
// TODO: Implement error handling using try/catch
const GetAllNewArticleResults = await GetAllNewArticle();
let promises = [];
GetAllNewArticleResults.map(e => {
promises.push(
htmlToJson.parse(
e.HTMLNewsCode,
{
title: function($doc) {
return textTruncate($doc.find("H2").text(), 50);
},
link: function($doc) {
return $doc.find("A").attr("href");
},
content: function($doc) {
return textTruncate($doc.find("P").text(), 80);
},
imageURL: function($doc) {
return $doc.find("img").attr("src");
}
},
function(err, result) {
return result;
}
)
);
});
const results = await Promise.all(promises);
setNewsCatalog(prev => [...prev, ...results]);
}
fetchNews();
}, []);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.