Run*_*ror 7 javascript typescript reactjs react-native
So I have a React Native application using TypeScript, with an error that's driving me crazy.
Basically, there is a Searchable List. It is initiated with an Array of values. Once the user types in a SearchBar, the initiated Array is filtered, returning an updated Array.
However, TypeScript gives me the error: Type '{ id: string; name: string; selected: boolean; }[]' provides no match for the signature '(prevState: undefined): undefined'.
I am confused because I don't know where this '(prevState: undefined): undefined'
actually comes from and why. Do you know what I am doing wrong here? Help will be much appreciated.
Here is the code:
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]);
Run Code Online (Sandbox Code Playgroud)
问题是,您已将其设置choicesList
为未定义。andgetChoicesList
在组件第一次初始化时调用,但在此之前,我们在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)
}, []);
Run Code Online (Sandbox Code Playgroud)
现在,您将拥有filteredChoicesList
所需的数据,并且不应出现任何编译错误。另一件事是,创建一个接口并any
在状态和定义时替换为该接口。
归档时间: |
|
查看次数: |
21300 次 |
最近记录: |