You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SPFX React WebPart组件无法设置自有状态问题咨询

解决SPFX React组件中TypeScript报错“Property 'date' does not exist on type 'Readonly<{}>'”

Hey there, let's break down why you're hitting this TypeScript error and fix it up quickly.

问题根源

你的WeatherApp组件是这么定义的:

export default class WeatherApp extends React.Component<IWeatherAppProps, {}>

这里的第二个泛型参数{}告诉TypeScript:这个组件的状态是一个空对象。所以当你尝试访问this.state.date时,TypeScript完全不知道这个属性存在,自然就抛出了错误。

修复步骤

你需要给组件的状态定义一个TypeScript接口,然后把这个接口替换掉原来的空对象作为泛型参数。

1. 定义状态接口

在WeatherApp.tsx的组件类上方,添加这个状态接口:

export interface IWeatherAppState {
  date: Date;
  status?: number; // 可选属性,因为初始状态下可能未定义
  weatherData?: any; // 如果想更严谨,可以给天气数据定义更具体的类型
}

2. 更新组件类的泛型参数

把组件的定义改成使用刚创建的状态接口:

export default class WeatherApp extends React.Component<IWeatherAppProps, IWeatherAppState>

3. 确保构造函数的状态符合接口类型

你的构造函数已经初始化了date属性,这和接口定义一致,现在TypeScript会正确识别所有状态属性了。

修改后的完整WeatherApp.tsx代码

import * as React from 'react';
import styles from './WeatherApp.module.scss';
import { IWeatherAppProps } from './IWeatherAppProps';
import { escape } from '@microsoft/sp-lodash-subset';
import getWeatherData from '../getWeatherData';

// 定义组件状态的TypeScript接口
export interface IWeatherAppState {
  date: Date;
  status?: number;
  weatherData?: any;
}

export default class WeatherApp extends React.Component<IWeatherAppProps, IWeatherAppState> {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  public render(): React.ReactElement<IWeatherAppProps> {
    console.log("This:", this);
    let weatherResponse;
    
    // 现在可以安全访问state中的status属性了
    if (this.state.status === 200) {
      console.log("Status state:", this.state.status);
      weatherResponse = <div>天气数据加载成功!</div>
    } else {
      weatherResponse = <div>Noch keine Daten.</div>
    }

    return (
      <div className={ styles.weatherApp }>
        <div className={ styles.container }>
          <div className={ styles.row }>
            <div className={ styles.column }>
              <span className={ styles.title }>Welcome to SharePoint Weather App!</span>
              <p className={ styles.subTitle }>Get Weather data from different locations.</p>
              <h2>Es ist {this.state.date.toLocaleTimeString()}.</h2>
              <p className={ styles.description }>{escape(this.props.description)}</p>
              <button className={ styles.button } onClick={() => getWeatherData(this.props.description).then(data => {
                console.log("Data Status:", data.status);
                // 统一更新多个状态属性
                this.setState({
                  status: data.status,
                  weatherData: data
                });
              })}>Get Data</button>
              <div id="response">
                {weatherResponse}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

额外优化建议

别用any来定义weatherData,可以给OpenWeatherMap的API响应定义一个更具体的接口,这样能获得更好的TypeScript智能提示和类型安全。比如:

export interface IWeatherData {
  status: number;
  name: string;
  main: {
    temp: number;
    humidity: number;
  };
  // 根据API返回的字段,添加其他需要的属性
}

然后把IWeatherAppState里的weatherData?: any改成weatherData?: IWeatherData即可。

内容的提问来源于stack exchange,提问作者MarcL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:47:48