React、Typescript 和 setState({ [name]: value }) 错误 [英] React, Typescript, and a setState({ [name]: value }) error
问题描述
过去几个月我一直在开发几个 create-react-app
+ TypeScript 应用程序.在某个时候(我可能升级了 lib),当 state 被赋予一个类型时,tslint 开始在 this.setState({ [name]: value })
上抛出错误.它曾经让它滑动(除非我快疯了......不是不可能的).
I have a couple create-react-app
+ TypeScript apps that I've been working on over the past few months. At some point (I probably upgraded the lib) tslint started throwing errors on this.setState({ [name]: value })
when state is given a type. It used to let it slide (unless I'm going crazy... not out of the question).
让 tslint 闭嘴的唯一方法是将状态类型更改为 any
,我不想这样做.如果我保存文件并让 yarn start
选择更改,它运行良好...所以我可以忽略 tslint 在 vscode 中抛出的错误.
The only way to get tslint to shut up about it, is to change the state type to any
, which I don't want to do. If I save the file and let yarn start
pick up the change, it runs fine... so I'm able to ignore the error that tslint throws in vscode.
我明白为什么 tslint 会抛出错误.我想知道是否可以设置规则来忽略此特定错误?
I understand WHY tslint is throwing an error. I'm wondering if there's a rule I can set to ignore this particular error?
我看到的示例(第 5 行):
Example of where I see this (line 5):
class MyComponent extends React.Component<IMyComponentProps, IMyComponentState> {
...
private handleOnChange = (event: any) => {
const { name, value } = event.target;
this.setState({ [name]: value }); <-- tslint no likey
}
错误:
[ts]'{ [x: number]: any; 类型的参数}' 不可分配给类型为 'IMyComponentState| 的参数((prevState: Readonly, pro...'.输入 '{ [x: number]: any;}' 不可分配到类型 'Pick
[ts] Argument of type '{ [x: number]: any; }' is not assignable to parameter of type 'IMyComponentState| ((prevState: Readonly, pro...'. Type '{ [x: number]: any; }' is not assignable to type 'Pick
推荐答案
您也可以在这里使用此解决方案:
You'd use this solution here too:
interface IState {
[key: string]: any; // or the type of your input
}
我想这比忽略警告要好.
I guess thats better than just ignoring the warnings.
这篇关于React、Typescript 和 setState({ [name]: value }) 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!