【问题标题】:Typescript/React - destructuring from this.state throws errorTypescript/React - 从 this.state 解构会引发错误
【发布时间】:2018-03-02 00:34:41
【问题描述】:

我的一个 React 组件中有以下方法:

getRandomColor(){
  const { colors }: { colors: any } = this.state;
  return colors[Math.floor(Math.random() * colors.length)];
}

但是,打字稿在解构语句中给我一个错误,我不知道为什么:

类型 'Readonly' 不能分配给类型 '{ colors: any; }'。 “只读”类型中缺少属性“颜色”。

谁能告诉我为什么?我肯定在构造函数中设置了this.state.colors,即使我没有,我也不完全确定它为什么会抛出这个错误。

【问题讨论】:

  • 所以你是trying to do this?似乎有效,也许您的状态设置不正确。
  • 我想我可能需要为构造函数中的this.state = 语句分配一个类型接口。出于某种原因,我认为类型会被自动推断
  • 它告诉你 Readonly 是一种我觉得很奇怪的类型。不认为 readonly 是一种类型。那或者我误解了错误信息。
  • 似乎在this.state 中找不到颜色变量的类型-当我将行更改为const colors = this.state.colors 时,错误变为:Property 'colors' does not exist on type 'Readonly<{}>'。但现在的问题是如何定义该类型?
  • 为什么它是只读的?呵呵。好吧,它应该是只读的,并使用 setState 进行修改,所以我想这有点道理。

标签: javascript reactjs typescript ecmascript-6


【解决方案1】:

在 TypeScript 中,类属性需要类型定义:

https://www.typescriptlang.org/docs/handbook/classes.html

this.state 作为我的组件类的属性也需要该类型定义:

interface State{
  colors: string[];
};

class ColorPicker extends React.Component {
  state: State;
  //...
}

添加后,错误消失了。

【讨论】:

    【解决方案2】:

    解构的正确语法是这样的:

    const { colors } = this.state;
    

    这假设有一个this.state.colors

    【讨论】:

    猜你喜欢
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2021-06-05
    • 2017-03-16
    • 1970-01-01
    • 2016-08-20
    相关资源
    最近更新 更多