ReactJS:'(bullets: never[]) => string[]' 类型的参数不可分配给 'SetStateAction<never[]>' 类型的参数
ReactJS: Argument of type '(bullets: never[]) => string[]' is not assignable to parameter of type 'SetStateAction<never[]>'
我正在从 API 中获取数据并从烦人的电子邮件中填充输入文本。我正在使用 bullet 和 setBullet 来维护状态。问题是我必须像这样定义一个初始项目进入使用状态:
const [bullet, setBullet] = useState(['Temp']);
但是这样定义它显然会添加“Temp”作为第一个输入,然后是所有电子邮件。但是如果我这样定义状态:
const [bullet, setBullet] = useState([]);
我在 onChangeHandler 和 useEffect 中的 map 函数中遇到错误。
const onChangeHandler = (index: number, value: string) => {
setBullet((bullets) =>
bullets.map((bullet, i) => (i === index ? value : bullet))
);
};
useEffect(() => {
fetch(
"https://reqres.in/api/users?page=2")
.then((res) => res.json())
.then((json) => {
json.data.map((data: any) => {
setBullet((bullets) => [...bullets, data.email]);
return console.log(data.email);
})
})
}, [])
setState 函数出错:
Argument of type '(bullets: never[]) => string[]' is not assignable to parameter of type 'SetStateAction<never[]>'.
Type '(bullets: never[]) => string[]' is not assignable to type '(prevState: never[]) => never[]'.
Type 'string[]' is not assignable to type 'never[]'.
Type 'string' is not assignable to type 'never'
总而言之,这就是我得到的。我想从中删除 'Temp' 项目符号。
任何帮助将不胜感激。
谢谢
您可以使用泛型将您想要的任何类型传递给 useState
。如果您不传入类型,useState
将尝试从初始值推断它。由于您传入的是一个空数组,因此无法自动推断类型,因此您必须手动进行:
const [bullet, setBullet] = useState<string[]>([]);
我正在从 API 中获取数据并从烦人的电子邮件中填充输入文本。我正在使用 bullet 和 setBullet 来维护状态。问题是我必须像这样定义一个初始项目进入使用状态:
const [bullet, setBullet] = useState(['Temp']);
但是这样定义它显然会添加“Temp”作为第一个输入,然后是所有电子邮件。但是如果我这样定义状态:
const [bullet, setBullet] = useState([]);
我在 onChangeHandler 和 useEffect 中的 map 函数中遇到错误。
const onChangeHandler = (index: number, value: string) => {
setBullet((bullets) =>
bullets.map((bullet, i) => (i === index ? value : bullet))
);
};
useEffect(() => {
fetch(
"https://reqres.in/api/users?page=2")
.then((res) => res.json())
.then((json) => {
json.data.map((data: any) => {
setBullet((bullets) => [...bullets, data.email]);
return console.log(data.email);
})
})
}, [])
setState 函数出错:
Argument of type '(bullets: never[]) => string[]' is not assignable to parameter of type 'SetStateAction<never[]>'.
Type '(bullets: never[]) => string[]' is not assignable to type '(prevState: never[]) => never[]'.
Type 'string[]' is not assignable to type 'never[]'.
Type 'string' is not assignable to type 'never'
总而言之,这就是我得到的。我想从中删除 'Temp' 项目符号。
任何帮助将不胜感激。
谢谢
您可以使用泛型将您想要的任何类型传递给 useState
。如果您不传入类型,useState
将尝试从初始值推断它。由于您传入的是一个空数组,因此无法自动推断类型,因此您必须手动进行:
const [bullet, setBullet] = useState<string[]>([]);