首页 > 解决方案 > 在渲染 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}
                        />
                    ) : (
                        <></>
                    )}

我收到一个错误,下拉选择器无法与defaultValuetestingCategories 中的任何标签匹配,因为它为空且尚未加载。我想我使用 setter 错误,因为我无法检查testingCategories' 的第一个元素是否已加载。我究竟做错了什么?

标签: javascriptreactjsreact-nativereact-hooksexpo

解决方案


您的useState定义与setTestingCategories稍后使用的位置之间存在类型不匹配。

在您的useState中,您将初始值定义为单个对象:

useState({
        label: null,
        value: null,
    });

但是,您可能想要的是一个空数组:

useState([]);

我还将您当前的行更改[{ label: null, value: null }]为空数组[]

然后,您的testingCategories标志将起作用,因为testingCategories最初将是一个长度为 0 的数组,这将无法通过真实性测试。


推荐阅读