我想使用useState
钩子来改变状态的值,但是我以前从未在功能组件中使用过useState
钩子,但是遇到了一个非常奇怪的错误。即使我将所有变量都定义为string[]
,它也会尝试将整个数组定义为number
。
import * as React from 'react'
import { NextPage } from 'next'
const IndexPage: NextPage = () => {
const [countries, setCountries] = React.useState<string[]>([])
return (
<>
{
["Dallas", "Oregon", "New York", "California"].map((x: string) =>
<button onClick={() => setCountries(countries.push(x))}>
<span>{x}</span> ^^^^^^^^^^^^^^^^^
</button>
)
}
<>
)
}
这是我得到的奇怪错误:
(method) Array<string>.push(...items: string[]): number
"Argument of type 'number' is not assignable to parameter of type 'SetStateAction<string[]>'.ts(2345)"
答案 0 :(得分:3)
Array.push返回一个数字,因此您必须将代码更改为此
import * as React from 'react'
import { NextPage } from 'next'
const IndexPage: NextPage = () => {
const [countries, setCountries] = React.useState<string[]>([])
return (
<>
{
["Dallas", "Oregon", "New York", "California"].map((x: string) =>
<button onClick={() => {
// either this
setCountries(countries.concat(x))
// or
setCountries([...countries, x]
}>
<span>{x}</span>
</button>
)
}
<>
)
}
答案 1 :(得分:1)
您需要将字符串数组传递给setCountries
<button onClick={() => setCountries([...countries, x])}>
答案 2 :(得分:0)
Array.push返回数字:
方法所基于的对象的新length属性 叫。
另外,您可能不想改变状态,请尝试setCountries(countries.concat(x))
答案 3 :(得分:0)
在您的情况下,setCountries
期望您传递字符串项数组,但是传递给它的是函数Array.push
的返回类型,该函数的类型为number
如果您只想在单击该按钮时删除一个国家/地区,则可以使用-
return (
<>
{
["Dallas", "Oregon", "New York", "California"].map((x: string) =>
<button onClick={() => setCountries(countries.concat(x))}>
<span>{x}</span>
</button>
)
}
<>
)