在應用程式中,我從 Firebase/Firestore 獲取資料,將其決議為介面并將物件添加到狀態陣列。之后我想渲染它。但是反應不會渲染陣列。我已經評論了代碼,您可以看到我認為它應該做什么。
const Tab1: React.FC = () => {
let spiceArray: singleSpice[] = [];
interface singleSpice {
spice: string,
grams: number,
}
useEffect(() => {
//fetch the data --> Works well
async function loadData() {
const data = await getCollections();
// Add the Data to the Spicearray --> Works
data.forEach((e: any) => spiceArray.push(e));
}
// Trigger Function onComponentMount
loadData();
// This function will never log "Worked" even tho the loadData is Async
if(spiceArray.length > 0){
console.log("Worked")
}
})
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>Tab 1</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent fullscreen>
<IonHeader collapse="condense">
<IonToolbar>
<IonTitle size="large">Tab 1</IonTitle>
</IonToolbar>
</IonHeader>
//Transfer the spiceArray to the next Child as Props --> Works
<CustomTab1 spices={spiceArray}/>
<ExploreContainer name="Tab 1 page" />
<IonButton onClick={() => console.log(spiceArray.length)}> Test me</IonButton>
</IonContent>
</IonPage>
);
};
export default Tab1;
孩子
//Interface for Props
interface Props {
spices: Spice[];
}
//Interface to get access to inner Attributes of the SpiceObjectArray
interface Spice {
spice: string;
grams: number;
}
const CustomTab1: React.FC<Props> = ({spices}: Props) => {
return (
<IonList>
//Conditional Render
{spices.length > 0 && spices.map(entry => <IonItem id={entry.spice}>{entry.spice}</IonItem>)}
<IonButton onClick={() => console.log(spices)}>Test</IonButton>
</IonList>
);
};
export default CustomTab1;
瘋狂的事情是。現在,當我按 F5 時,IonicApp 沒有顯示任何香料。但是,當我更改 CustomTab1-Component 上的 IoNButton 內的文本并保存簡單的更改時,香料會被渲染。但是,如果我按 F5 重繪 應用程式,一切都會再次消失。我怎樣才能讓應用程式等到 API 傳遞資料?
uj5u.com熱心網友回復:
當變數發生變化時,React 不會重新渲染。您說您將獲取的物件傳遞給“狀態陣列”,但spiceArray不是反應狀態。在功能組件中,狀態是用 useState 宣告的。
當您的頁面最初加載時,沒有資料,您有正確的想法來檢查是否有任何資料,然后再嘗試映射/渲染它。但是為了讓組件重新渲染并重新檢查香料陣列中是否有任何內容,您必須使用狀態并更改狀態。
const [spiceArray, setSpiceArray] = useState<singleSpice[] | null>(null)
useEffect(() => {
//fetch the data --> Works well
async function loadData() {
const data = await getCollections();
// Add the Data to the Spicearray --> Works
setSpiceArray(data)
}
// Trigger Function onComponentMount
loadData();
// This function will never log "Worked" even tho the loadData is Async
if (spiceArray.length > 0) {
console.log("Worked");
}
}, []);
您的代碼應如下所示并將子組件渲染邏輯更改為:
{spices && spices.map(entry => <IonItem id={entry.spice}>{entry.spice}</IonItem>)}
請記住其他幾件事:
- 如果您希望 useEffect 僅在掛載時運行(通常在獲取資料時就是這種情況),您需要一個空的依賴陣列。
- 控制臺記錄 spiceArray 或檢查 spiceArray.length 是否不為 0 在 useEffect 中仍然不起作用,因為 react 中的狀態更新是異步的/更新下一次渲染狀態的請求。因此,變化不會立即反映/觀察到
uj5u.com熱心網友回復:
spiceArray 不是狀態,無法重新渲染您的子組件。
將變數更改為狀態
uj5u.com熱心網友回復:
你不必等待loadData();嗎?
然后繼續if(spiceArray.length > 0){
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/424041.html
