javascript - 在渲染 React Native 之前检查值是否未定义
问题描述
我正在使用(下拉选择器库)显示从 api 调用获得的数据类别。我正在等待 api 获取数据,然后计划显示类别。问题是我需要先重新格式化数据并在渲染之前使用钩子,但我无法正确处理。
选择器的数据如何:
items={[
{label: 'USA', value: 'usa'},
{label: 'UK', value: 'uk'},
{label: 'France', value: 'france'/>},
]}
我的钩子:
const [country, setCountry] = useState("0");
const [categoryData, setCategoryData] = useState();
const [testingCategories, setTestingCategories] = useState({
label: null,
value: null,
});
我的效果挂钩并重新格式化数据:
//this hook calls api and sets the data to categories data of my type
useEffect(() => {
getData(api.API_GET_DEPS, setIsLoading, setCategoryData);
}, []);
//this hooks reformats the data into acceptable format for picker
useEffect(() => {
setTestingCategories(
categoryData
? categoryData.map((item) => ({
label: item.DEPNAME, //label
value: item.DEPID, //value
}))
: [{ label: null, value: null }]
);
}, [categoryData]);
我的下拉渲染:
<View style={styles.container}>
{testingCategories ? (
<DropDownPicker
dropDownMaxHeight={300}
placeholder="All"
defaultValue={country}
items={testingCategories}
containerStyle={{ height: 50 }}
style={{ backgroundColor: "#fafafa" }}
itemStyle={{
justifyContent: "flex-start",
}}
dropDownStyle={{ backgroundColor: "#fafafa" }}
onChangeItem={(item) => {
console.log("changed");
}}
onOpen={() => setContainerOpacity(0.1)}
onClose={() => setContainerOpacity(1)}
labelStyle={{
fontSize: 16,
color: colors.dark,
fontWeight: "600",
}}
arrowSize={25}
arrowColor={colors.dark}
/>
) : (
<></>
)}
我收到一个错误,下拉选择器无法与defaultValue
testingCategories 中的任何标签匹配,因为它为空且尚未加载。我想我使用 setter 错误,因为我无法检查testingCategories
' 的第一个元素是否已加载。我究竟做错了什么?
解决方案
您的useState
定义与setTestingCategories
稍后使用的位置之间存在类型不匹配。
在您的useState
中,您将初始值定义为单个对象:
useState({
label: null,
value: null,
});
但是,您可能想要的是一个空数组:
useState([]);
我还将您当前的行更改[{ label: null, value: null }]
为空数组[]
。
然后,您的testingCategories
标志将起作用,因为testingCategories
最初将是一个长度为 0 的数组,这将无法通过真实性测试。
推荐阅读
- javascript - 如何在节点js中使用foreach附加查询响应作为对象
- javascript - Javascript:对数组中每种类型的计数和排序数
- azure-devops - Devops Yaml 在另一个变量中获取变量的值
- windows - Windows 2012 r2 自定义映像存在 NTP 问题。重新启动时浪费时间
- sql-server - SQL Server 2016 中登录事件中记录的客户端 IP 对于远程连接为 NULL
- python - 虽然功能进入其他同时不起作用
- flutter - 非抽象类“_LoadingScreenState”缺少实现
- dask - 如何在最后一步结合 dask 期货?
- ios - 如何从firebase数据库中检索子数组
- javascript - 使用按钮更改内容