首页 > 解决方案 > React Native 功能组件中的 UseEffect 未被调用

问题描述

我在 React Native 中有以下功能组件,它调用另一个组件 <ProfileQuestionsEntryComponent questionArray={data.qDescription} />

我花了几天时间试图找出为什么当我加载页面时不再调用 useeffect。它只是说渲染返回null。

import React, { useState, useEffect } from 'react';
import { ScrollView, StyleSheet, View, Button } from 'react-native';
import {List } from 'react-native-paper';
import ProfileQuestionsEntryComponent from '../../assets/Components/ProfileQuestionsEntry'

const HomeScreen = ({ }) => {
  const [QuestionsList, setQuestionsList] = React.useState([]);
    useEffect(() => {
      
      console.log("called");
        try {
 
             fetch('http://SomeAPIThatreturnsJSON/listquestions/4/1').then((response) => response.json()).then((json) => {
             setQuestionsList(json);
 
         }).catch((error) => {
             console.error(error);
         });
 
     } catch(err) {
         console.log("Error fetching data-----------", err);
     }
       
    }, []);

  const [expanded, setExpanded] = React.useState(true);
  const handlePress = () => setExpanded(!expanded);
  QuestionsList.map((data) => {
    return (
    <View style={styles.container}>
    <ScrollView contentContainerStyle={{ paddingVertical: 20 }}>
    <List.Section title="Level 1 Questions! ">
      <List.Accordion   title="This is an accordian??"        >
           <ProfileQuestionsEntryComponent questionArray={data.qDescription} /> 
      </List.Accordion>
    </List.Section>
    </ScrollView>
    </View>
    )
  });
};
 

const styles = StyleSheet.create({
  container: {
    paddingTop: 30,
    marginLeft: 20, 
    marginRight: 20,
    flex: 1,
  },
  buttonView: {
    display: 'flex',
    justifyContent: 'center',
    flexDirection: 'row',
    marginTop: 10,
  },
});
 
export default HomeScreen;

标签: reactjsreact-nativereact-hooksuse-effect

解决方案


你需要从你的组件中返回一些东西。QuestionsList首先是空的。所以你的组件不会返回任何东西。如果 QuestionsList 为空,您必须返回一些东西

if (QuestionsList.length === 0) return null;

在您的映射内容之上,只需检查是否QuestionsList为空然后返回null。由于您没有返回任何内容,因此您会收到错误消息。您需要先修复该错误,然后检查是否useEffect被调用。

或者,如果QuestionsList为空,您可以显示加载指示器。

if (QuestionsList.length === 0) return <p>Loading ...</p>;

推荐阅读