reactjs - 如何使用 useState 声明一个字符串数组,然后在使用 Typescript 时对其进行更新?
问题描述
我有以下
interface ISTx {
tx: Array<string>,
setTx: any
}
const [tx, setTx] = useState<ISTx>([]) //Argument of type 'never[]' is not assignable to parameter of type 'ISTx
setTx(oldArr => [...oldArr , txHash]) //Argument of type '(oldArr: ISTx) => any[]' is not assignable to parameter of type 'SetStateAction<ISTx>
但是我收到了上面块代码中注释的错误。
我基本上试图创建一个字符串数组的状态,并将新字符串推入其中。
解决方案
const [tx, setTx] = useState<string[]>([]);
您在尖括号 (<>) 之间声明您的状态类型。React 将为tx
和提供必要的类型setTx
。