javascript - 渲染的钩子比之前的渲染更多,只发生在一个组件中?
问题描述
在我的 react native 组件中,我正在尝试使用钩子Turnos
从异步存储中获取项目:useEffect()
export default function Turnos({ navigation }: any) {
const { loading, error, data, refetch } = useQuery(GET_TURNS, {
onError: () =>
Alert.alert(
"Error",
"Hubo un error al conectarse. Por favor, verificá tu conexión a internet"
),
pollInterval: 3000,
fetchPolicy: "no-cache",
});
if (loading) {
return <Loader />;
}
if (error) {
Alert.alert(
"Error",
"Hubo un error al conectarse. Por favor, verificá tu conexión a internet"
);
return null;
}
const myTurns = data.getTurnsForUser.filter(
(e: any) => e.fullfilled === false
);
const getUserId = async () => {
await AsyncStorage.getItem("USER_ID").then((res) => {
console.log(res);
});
};
useEffect(() => {
getUserId();
}, []);
return (
<View style={styles.container}>
<FlatList
contentContainerStyle={styles.turnList}
style={styles.turnList}
data={myTurns}
renderItem={(turn) => (
<Turno
title={turn.item.store.name}
peopleQueue={turn.item.store.turns.length} // how many people are in the queue
></Turno>
)}
keyExtractor={(turn) => turn.id}
refreshControl={
<RefreshControl
refreshing={false}
onRefresh={() => {
try {
refetch();
} catch (error) {
Alert.alert("Error", String(error));
}
}}
></RefreshControl>
}
ListEmptyComponent={
<View style={styles.listEmptyContainer}>
<PrimaryText>No hay turnos por ahora...</PrimaryText>
</View>
}
></FlatList>
</View>
);
}
但是,我不断收到错误消息:Renedered more hooks than during the previous render
. 这真的很奇怪,因为我在另一个组件中使用完全相同的代码并且它工作得很好:
const loadActiveTurn = async () => {
await AsyncStorage.getItem("HAS_ACTIVE_TURN").then((check) => {
check === "1" ? setHasActiveTurns(true) : setHasActiveTurns(false);
});
};
useEffect(() => {
loadActiveTurn();
}, []);
我究竟做错了什么?
解决方案
我意识到错误是什么:永远不要useEffect()
在条件语句内部或之后调用钩子,就像我之后所做的那样:
if (loading) {
return <Loader />;
}
if (error) {
Alert.alert(
"Error",
"Hubo un error al conectarse. Por favor, verificá tu conexión a internet"
);
return null;
}
只是把它放在顶部固定它。
推荐阅读
- bluetooth - 获取连接到蓝牙 HC-06 和 Arduino 的设备名称
- c - 使用全局变量的线程问题
- kibana - Kibana filter regex 'string starts with' doesn't work
- r - 闪亮应用程序中的 Source()
- python - Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org
- sails.js - 如何在 Sails JS 控制器中操作 JSON 数据
- ruby-on-rails - Rails - 无法自动加载常量 - Transaction Express API 调用
- wso2is - 有没有办法在 Identity Server 中跟踪谁最后通过 IDP 访问资源?
- r - 使用 cdo 的气候数据趋势的显着性价值
- android-studio - 如何找到 Flutter SDK 的路径