reactjs - 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;
解决方案
你需要从你的组件中返回一些东西。QuestionsList
首先是空的。所以你的组件不会返回任何东西。如果 QuestionsList 为空,您必须返回一些东西
if (QuestionsList.length === 0) return null;
在您的映射内容之上,只需检查是否QuestionsList
为空然后返回null
。由于您没有返回任何内容,因此您会收到错误消息。您需要先修复该错误,然后检查是否useEffect
被调用。
或者,如果QuestionsList
为空,您可以显示加载指示器。
if (QuestionsList.length === 0) return <p>Loading ...</p>;
推荐阅读
- php - 如何保持会话 fb api 图以避免(#4)应用程序请求限制达到
- c - 用文件的内容填充字符串数组
- javascript - “未捕获的语法错误:意外的标记:”在“x:element.position().get(x)”中
- python - 尝试打开多个浏览器不断收到错误脚本无法运行
- sql - SQL 创建函数在返回部分出错
- php - 如何将数值添加到值而不在php中添加或减去它
- reactjs - 带有 React 路由的 EventHandler
- sql - 如何尽可能透明地将现有 Postgres 表迁移到分区表?
- c# - == 是否总是对 SQL 中的二进制文件执行 SequenceEqual()?
- sql - 如何在sql(oracle)中将元素添加到嵌套表中?