【问题标题】:Property "value" does not exist on type Readonly只读类型上不存在属性“值”
【发布时间】:2021-04-12 22:53:28
【问题描述】:

我正在学习如何使用 React 作为前端和 Spring 作为后端来开发应用程序。在开发示例应用程序时,我遇到了如下错误:

       `(26,28): Property "value" does not exist on type 'Readonly<{}>`

此错误是由我的 App.tsx 文件生成的,该文件包含 JSX 中的 React 组件定义。 状态为“值”的类组件定义如下。

class App extends React.component{
        constructor(props:any) {
             super(props);
             this.state = {
             value:[],
             isLoading:false
          };
       }
        ...
25      render(){
26        const value = this.state.value;
27        const isLoading = this.state.isLoading;
          ... 
    }
   }//End of Class*

我不明白出了什么问题。有人可以帮我从不同的角度看待它,以便可以以不同的方式解决这个问题吗?

【问题讨论】:

  • 请更改标题以描述问题或疑问,而不是您的项目。
  • 感谢您的宝贵建议。

标签: reactjs typescript


【解决方案1】:

您是否为您的state 声明了一个接口?

看看Hello React and TypeScript,它展示了一个使用 React 组件接口的例子。

我怀疑你错过了这样的东西:

interface IMyComponentProps {
    someDefaultValue: string
}

interface IMyComponentState {
    someValue: string
}

class App extends React.Component<IMyComponentProps, IMyComponentState> {
  // ...
}

【讨论】:

  • 非常感谢,我所要做的就是 React.Component 而不是 React.Component。但是从这篇文章中得到了灵感……再次感谢。
【解决方案2】:

请您按以下方式尝试。

class App extends React.component<{},any>{ //your code}

【讨论】:

    【解决方案3】:
        export default class ReactTodoWebpart extends React.Component<IReactTodoWebpartProps,any> {
      /**
       *
       */
      constructor(props:IReactTodoWebpartProps) {
        super(props);
        this.state={
          todoItems:[]
        };
        this.props.todoClient.getItems().then(resolvedItems=>{
          this.setState({
            todoItems: resolvedItems,
    
          })
        });
    
      }
    // I also face this issue and fixed it by using any in the second argument
    

    【讨论】:

      猜你喜欢
      • 2018-05-13
      • 2020-05-03
      • 2018-12-04
      • 2021-02-03
      • 2019-02-14
      • 2020-01-29
      • 2017-06-23
      • 2019-02-17
      • 2017-10-06
      相关资源
      最近更新 更多