【问题标题】:Property 'shouldComponentUpdate' is not assignable to the same property属性“shouldComponentUpdate”不可分配给同一属性
【发布时间】:2018-12-05 13:01:39
【问题描述】:

我在使用 shouldComponentUpdate 的 TypeScript 中遇到错误:

“Hello”类型中的属性“shouldComponentUpdate”不能分配给基类型 Component<IProps, any, any> 中的相同属性。

在组件中:

import React, { Component } from 'react'

class Hello extends Component<IProps, any> {
  shouldComponentUpdate(nextProps: IProps) { // error here
    console.log(nextProps, 'nextProps')
  }

  ....// some code
}

谁能解释一下我做错了什么?

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    将 React 与 TypeScript 一起使用有点烦人,因为今天的最后一个不包含所有必需的错误描述提示。因此,您的案例中的错误可能与来自shouldComponentUpdate 方法的未完成的return 调用绑定。

    接下来试试看会发生什么:

      shouldComponentUpdate(nextProps: IProps) { // error here
        console.log(nextProps, 'nextProps')
        return true
      }
    

    【讨论】:

    • 谢谢你,对我有帮助!
    【解决方案2】:

    我相信这是因为 shouldComponentUpdate 预计会返回一个布尔值。您正在返回 void,因为您没有明确返回任何内容。默认情况下返回 true,因此只需将其添加为函数中的最终语句即可解决问题。

    有关更多信息,请参阅例如反应文档:https://reactjs.org/docs/react-component.html#shouldcomponentupdate

    【讨论】:

      【解决方案3】:

      Typescript 希望您定义每个传递参数的类型和returned 值的类型。如果你的函数没有返回语句,那么你可以使用: void

        shouldComponentUpdate(nextProps: IProps): void {
          console.log(nextProps, 'nextProps')
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-22
        • 2018-08-25
        相关资源
        最近更新 更多