首页 > 解决方案 > 渲染的钩子比之前的渲染更多,只发生在一个组件中?

问题描述

在我的 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();
  }, []);

我究竟做错了什么?

标签: javascriptreactjsreact-nativeexpo

解决方案


我意识到错误是什么:永远不要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;
  }

只是把它放在顶部固定它。


推荐阅读