I am trying to get accustomed with React Native. Currently I have these nested FlatLists (where the first level displays a list of RenderedOrders
, whereas these RenderedOrders
themselves have a FlatList within them).
This is the main screen:
const ActiveScreen = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
const [isLoadingApi, setLoadingApi] = useState(true);
const [orderData, setOrderData] = useState([])
/* Fetch currently taken orders */
useEffect(() => {
getTakenOrders()
.then((data) => setData(data))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
/* Fetch order info from API */
useEffect(() => {
fetch('https://alessandro-visualizr.herokuapp.com/api/orders/NEFACTURAT')
.then((response) => response.json())
.then((json) => setOrderData(json))
.catch((error) => console.error(error))
.finally(() => setLoadingApi(false));
}, []);
return (
<View style={{ flex: 1, padding: 24 }}>
{isLoading || isLoadingApi ? <ActivityIndicator/> : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (RenderedOrder(item, orderData)) }
/>
)}
</View>
);
}
export default ActiveScreen;
While this is the above-mentioned component:
import React, {useEffect, useState} from "react";
import {FlatList, Text, View} from "react-native";
import {removeTakenOrder} from "../screens/OrderScreen";
function RenderedOrder(orderId, orderData) {
const [triggered, setTriggered] = useState(true);
return (
<View
style={{ flex: 1}}
>
<View
style={{ fontSize: 20, borderRadius: 5, borderWidth: 1,
marginBottom: 10, padding: 10, backgroundColor: 'rgba(34, 139, 34, 0.75)', color: 'black',
flex: 1 }}
>
<Text
style={{ fontSize: 24 }}
>
#{orderId}
</Text>
<View
style={{ alignItems: 'flex-end' }}
>
<Text
style={{ fontWeight: 'bold', color: 'red', fontSize: 20 }}
onPress={() => removeTakenOrder(orderId)
.then(() => alert("Order #" + orderId + " has been removed"))
}
>
X
</Text>
</View>
</View>
{true &&
<FlatList
data={orderData.filter((order) => (order.orderId === orderId))[0].products}
keyExtractor={({ id }, index) => id}
listKey = {orderId}
renderItem={({ item }) => (
<View>
<Text
style={{ fontSize: 18, padding: 5 }}
>
- {item.name}
<Text style={{ fontWeight: 'bold' }}> x{item.quantity} </Text>
</Text>
</View>
)}
/>
}
</View>
);
}
export default RenderedOrder;
However, when running this example I am confronted with this issue (due to RenderedOrder
's state declaration):
Invalid hook call. Hooks can only be called inside the body of a function component.
I understand that in React, states can only be used within function and not class components. However I admit the differences between these two are not that clear to me. Am I commiting a mistake here?
question from:
https://stackoverflow.com/questions/66047417/react-native-invalid-hook-calls 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…