简体   繁体   English

如何在 Typescript 中将具有动态键的对象设置为 React 状态

[英]How to set an an object with a dynamic key as React state in Typescript

I am using React and Typescript and need to create an object with a dynamic key that has two pre-defined properties.我正在使用 React 和 Typescript,并且需要使用具有两个预定义属性的动态键创建一个对象。 The field is dynamic so I can't pre-define it in Typescript.该字段是动态的,因此我无法在 Typescript 中预先定义它。 The structure I have attempted to implement in the interface is:我试图在接口中实现的结构是:

[field: string]: {
   property1: string,
   property2: string
}

I then want to be able to dynamically set the key of this object.然后我希望能够动态设置这个对象的键。 Such as,如,

let item: string = "randomTest"

 this.setState({
    [item].property1: "test value 1"
 })

And access it through:并通过以下方式访问它:

this.state[item].property1

However, when I attempt to implement this structure in the Typescript interface, the state keys that are not in the dynamic object throw an error saying they are "not assignable to string index type '{property1: string}'. For example, testKey1 below would throw this error:但是,当我尝试在 Typescript 接口中实现此结构时,不在动态对象中的状态键会抛出错误,指出它们“不可分配给字符串索引类型 '{property1: string}'。例如,下面的 testKey1会抛出这个错误:

[field: string]: {
   property1: string,
   property2: string
};
testKey1: string;

This error seems to be saying that testKey1 is in the [field] object even though it isn't.这个错误似乎是说 testKey1 在 [field] 对象中,即使它不是。

How can I effectively define an object with a dynamic key as React state in Typescript?如何有效地将具有动态键的对象定义为 Typescript 中的 React 状态?

在 testKey1 之前添加一个 semecon: string;

You can use the Record built-in type added in TypeScript 2.1.您可以使用 TypeScript 2.1 中添加的 Record 内置类型。 Record记录

interface MyObject {
  property1: string;
  property2: string;
}

type DynamicObject = Record<string, MyObject>;

Replace代替

[field: string]: {
   property1: string,
   property2: string
}

by经过

    interface Anything {
      [key: string]: any;
    }

And when you're calling then: do this当你打电话时:这样做

let item = { property1: "randomTest", property2: "randomTest1", property3: "randomTest3"}

 this.setState({
    [item].property1: "test value 1"
 })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM