所以我有一个使用TypeScript的React Native应用程序,出现的错误使我发疯。
基本上,有一个可搜索列表。它由值数组启动。用户键入SearchBar后,将过滤启动的数组,并返回更新的数组。
但是,TypeScript给了我错误:Type '{ id: string; name: string; selected: boolean; }[]' provides no match for the signature '(prevState: undefined): undefined'.
我很困惑,因为我不知道这个'(prevState: undefined): undefined'
的实际来源和原因。你知道我在做什么错吗?帮助将不胜感激。
这是代码:
const defaultChoices = [
{
id: '1',
name: 'default',
selected: false,
},
];
let choicesList;
const getChoicesList = () => {
if (listName === 'include') {
choicesList = Object.values(includeChoices).map(choice => ({
...choice,
}));
} else if (listName === 'exclude') {
choicesList = Object.values(excludeChoices).map(choice => ({
...choice,
}));
}
};
const [filteredChoicesList, setFilteredChoicesList] = useState(choicesList);
useEffect(() => {
getChoicesList();
}, []);
useEffect(() => {
let choices = defaultChoices;
if (listName === 'include') {
choices = includeChoices;
} else if (listName === 'exclude') {
choices = excludeChoices;
} else {
choices = defaultChoices;
}
const newChoices = choices.filter(item => {
const itemData = `${item.name.toUpperCase()}`; // ignore Uppercase/Lowercase and make equal
const textData = query.toUpperCase();
return itemData.indexOf(textData) > -1;
});
setFilteredChoicesList(newChoices); // error occurs for "newChoices"
}, [effect]);
答案 0 :(得分:3)
问题是,您已将choicesList
设置为未定义。和getChoicesList
在组件的首次初始化时被调用,但在此之前,我们将状态choicesList
设置为未定义状态。
将代码部分更新为
let choicesList: any[] = [];
const getChoicesList = () => {
let data: any[] = [];
if (listName === 'include') {
data = Object.values(includeChoices).map(choice => ({
...choice,
}));
} else if (listName === 'exclude') {
data = Object.values(excludeChoices).map(choice => ({
...choice,
}));
}
return data;
};
const [filteredChoicesList, setFilteredChoicesList] = useState<any[]>(choicesList);
useEffect(() => {
const updatedList = getChoicesList();
setFilteredChoicesList(updatedList)
}, []);
现在,您将拥有filteredChoicesList
,其中包含所需的数据,并且不会出现任何编译错误。
另一件事是,创建一个接口,并在状态和定义时用该接口替换any
。