Reactjs Typescript spfx错误:属性';新闻';不存在于类型';只读<;{}>;
我正在尝试创建一个spfx react组件,该组件将向浏览器显示rss提要。我在一个游戏场中使用了这个,但是spfx使用了typescript,不知道如何处理下面的类型错误 RssFeed.tsReactjs Typescript spfx错误:属性';新闻';不存在于类型';只读<;{}>;,reactjs,typescript,spfx,Reactjs,Typescript,Spfx,我正在尝试创建一个spfx react组件,该组件将向浏览器显示rss提要。我在一个游戏场中使用了这个,但是spfx使用了typescript,不知道如何处理下面的类型错误 RssFeed.ts import * as React from 'react'; import styles from './RssFeed.module.scss'; import { IRssFeedProps } from './IRssFeedProps'; import { escape } from '@mi
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>
);
}
}
这就是错误:
错误-[tsc]src/webparts/rssFeed/components/rssFeed.tsx(47,25):错误TS2339:类型“Readonly”上不存在属性“news”。创建组件时需要添加到状态的键入中:
interface IRssFeedState { news: any[] };
class RssFeed extends React.Component<IRssFeedProps, IRssFeedState> {
...
}
接口IRssFeedState{news:any[]};
类RssFeed扩展了React.Component{
...
}
此外,您通常应该有一个定义良好的类型,而不是为组件状态传递空接口的
any
interface ComponentProps{
firstProp: string;
}
interface ComponentState {
firstPropsOnState: string;
}
那你就可以这样用了
class MyComponent extends React.Component<ComponentProps, ComponentState> {...}
类MyComponent扩展了React.Component{…}
由于您正在传递一个空接口,TypeScript将抱怨state上的news属性不存在,因为您声明了一个空状态。只要将该属性添加到接口中,并在创建组件时将其向下传递,它就会工作
在文档中,它们没有为状态定义接口的expample,这可能会误导TypeScript的新手。您在那里传递的第二个泛型类型是您的实际状态
希望它能让你明白
class MyComponent extends React.Component<ComponentProps, ComponentState> {...}