有人可以帮我弄清楚为什么当我使用 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 数组,并将其推送到那里
感谢天使萨拉查 我尝试更改我的代码
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();
}, []);