[英]How to set an object key inside a state object in React Hooks
[英]How to set an an object with a dynamic key as React state in Typescript
我正在使用 React 和 Typescript,並且需要使用具有兩個預定義屬性的動態鍵創建一個對象。 該字段是動態的,因此我無法在 Typescript 中預先定義它。 我試圖在接口中實現的結構是:
[field: string]: {
property1: string,
property2: string
}
然后我希望能夠動態設置這個對象的鍵。 如,
let item: string = "randomTest"
this.setState({
[item].property1: "test value 1"
})
並通過以下方式訪問它:
this.state[item].property1
但是,當我嘗試在 Typescript 接口中實現此結構時,不在動態對象中的狀態鍵會拋出錯誤,指出它們“不可分配給字符串索引類型 '{property1: string}'。例如,下面的 testKey1會拋出這個錯誤:
[field: string]: {
property1: string,
property2: string
};
testKey1: string;
這個錯誤似乎是說 testKey1 在 [field] 對象中,即使它不是。
如何有效地將具有動態鍵的對象定義為 Typescript 中的 React 狀態?
在 testKey1 之前添加一個 semecon: string;
您可以使用 TypeScript 2.1 中添加的 Record 內置類型。 記錄
interface MyObject {
property1: string;
property2: string;
}
type DynamicObject = Record<string, MyObject>;
代替
[field: string]: {
property1: string,
property2: string
}
經過
interface Anything {
[key: string]: any;
}
當你打電話時:這樣做
let item = { property1: "randomTest", property2: "randomTest1", property3: "randomTest3"}
this.setState({
[item].property1: "test value 1"
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.