我正在使用 (Drop Down Picker library) 来显示我从 api 调用中获得的数据类别。我正在等待 api 获取数据,然后计划显示类别。问题是我需要先重新格式化数据并在渲染之前使用钩子,但我无法正确处理。
picker 的数据是什么样子的:
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
的第一个元素是否已加载。我做错了什么?
答案 0 :(得分:1)
您的 useState
定义与您稍后使用 setTestingCategories
的位置之间存在打字不匹配。
在您的 useState
中,您将初始值定义为单个对象:
useState({
label: null,
value: null,
});
然而,你可能想要的是一个空数组:
useState([]);
我还会将您当前的行 [{ label: null, value: null }]
更改为一个空数组 []
。
然后,您的 testingCategories
标志将起作用,因为 testingCategories
最初将是一个长度为 0 的数组,这将无法通过真实性测试。