【问题标题】:Typescript spfx error: Property 'news' does not exist on type 'Readonly<{}>Typescript spfx 错误:“只读”类型上不存在属性“新闻”<{}>
【发布时间】:2020-01-29 02:38:15
【问题描述】:

我正在尝试创建一个 spfx 反应组件,它将向浏览器显示 rss 提要。我有这个在操场上工作,但 spfx 使用打字稿,不知道如何解决下面的类型错误。

RssFeed.ts

import * as React from 'react';
import styles from './RssFeed.module.scss';
import { IRssFeedProps } from './IRssFeedProps';
import { escape } from '@microsoft/sp-lodash-subset';
import * as $ from "jquery";
import { string } from 'prop-types';

export default class RssFeed extends React.Component<IRssFeedProps,        
{}> {

constructor(props) {
    super(props);
    this.state = { news: [] };
}

componentDidMount() {
    this.getNews();
}

getNews() {
    $.get(
  "https://www.feed.co.uk/news/feed",
  function(data) {
    var $xml = $(data);
    var items = [];

    $xml.find("item").each(function() {
      var $this = $(this);
      items.push({
        title: $this.find("title").text(),
        link: $this.find("link").text()
        // link: $this.find("link").text(),
      });
    });

    this.setState({ news: items }, function() {
      // callback function to check what items going onto the array
      console.log(this.state.news);
    });
  }.bind(this),
  "xml"
);
}

 public render(): React.ReactElement<IRssFeedProps> {
  return (
  <div className={ styles.rssFeed }>
        {this.state.news.map(item => (
        <div className="panel" key={item.title}>
          <h2 className="panel-title">
            {item.title}
          </h2>
          <span>{item.link}</span>
        </div>
      ))}
  </div>
);
}
}

IRssFeedProps.ts

export interface IRssFeedProps {
description: string;
}

这是错误: 错误 - [tsc] src/webparts/rssFeed/components/RssFeed.tsx(47,25):错误 TS2339:“Readonly”类型上不存在属性“news”。

【问题讨论】:

    标签: reactjs typescript spfx


    【解决方案1】:

    您正在为组件状态传递一个空接口。

    interface ComponentProps{
      firstProp: string;
    }
    
    interface ComponentState {
      firstPropsOnState: string;
    }
    

    那么你可以这样使用它

    class MyComponent extends React.Component<ComponentProps, ComponentState> {...}
    

    由于您传递的是空接口,TypeScript 会抱怨 state 上的 news 属性不存在,因为您声明了一个空状态。只需将该属性添加到您的界面并在您创建组件时将其传递下来,它就会起作用。

    https://www.typescriptlang.org/docs/handbook/react-&-webpack.html#write-some-code

    在文档中,他们没有为状态定义接口的示例,这可能会误导 TypeScript 的新手。您传递的第二种泛型类型是您的实际状态。

    希望它能让你明白。

    【讨论】:

      【解决方案2】:

      你需要在创建组件时添加到类型的状态:

      interface IRssFeedState { news: any[] };
      
      class RssFeed extends React.Component<IRssFeedProps, IRssFeedState> {
      ...
      }
      

      此外,您通常应该有一个除any 之外的明确定义的类型。

      【讨论】:

        猜你喜欢
        • 2020-05-03
        • 2023-02-21
        • 2019-04-12
        • 2020-07-09
        • 2019-10-20
        • 2021-09-26
        • 2018-12-04
        • 2018-05-13
        • 1970-01-01
        相关资源
        最近更新 更多