我剛剛開始反應并試圖從我的 api 中獲取一些資料,但是更改狀態不會觸發組件的重新渲染。我的組件中的 useeffect 函式中有一些代碼可以獲取我的 api 然后設定狀態作為道具傳遞。這是在 App.js 上宣告的狀態:
const [username,setUsername] = useState("");
const [all,setAll] = useState([]);
const [today,setToday] = useState([]);
我將它們和它們的設定函式作為道具傳遞給 APP.js,在那里我使用 useeffect 函式來獲取資料并設定狀態。這是組件代碼的開頭:
const APP = ({username,all,setAll,today,setToday}) => {
useEffect(() => {
axios.get(`http://localhost:3001/api/${username}`)
.then(response =>{
let data = [response.data];
setAll(data[0]);
console.log(all);
const t = all.filter((task) => task.title === "a");
setToday(t);
console.log(today);
});
}, []);
問題是,資料獲取沒有問題,setAll 也可以作業并觸發重新渲染,但 setToday 什么也不做(保證有一個標題等于“a”的任務)。當我控制臺日志 { all} 在 useEffect 的第五行中,它只是列印一個空陣列,即使重新渲染發生了,并且在重新渲染后我會在頁面中顯示 {all} 的任務。是因為當它到達倒數第二行時,{all} 的任務還沒有設定嗎?如果是這種情況,我如何在過濾任務然后設定其他狀態之前等待?我知道有一些與此類似的問題,但這些問題中的任何答案都沒有幫助我。
uj5u.com熱心網友回復:
setAll(data[0]);
const t = all.filter((task) => task.title === "a");
問題基本上是在你宣告的時候const t = all.filter((task) => task.title === "a");, all 仍然是一個空陣列。
看,當你使用時setAll,它基本上是在告訴 react:嘿,當你完成渲染時,設定all為 value data[0]。這不會立即發生,而是在下一個回圈中發生。
如果我是你,我會怎么做:
const APP = ({username,all,setAll,today,setToday}) => {
useEffect(() => {
axios.get(`http://localhost:3001/api/${username}`)
.then(response =>{
const data = [response.data];
const responseAll = data[0];
const t = responseAll.filter((task) => task.title === "a");
setAll(responseAll);
setToday(t);
});
}, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/330763.html
標籤:javascript 反应
上一篇:具有太多道具的React重構組件
下一篇:如何在反應中將功能傳輸到功能組件
