【问题标题】:How to define a property to avoid: Property 'X' does not exist on type 'Y'如何定义要避免的属性:类型“Y”上不存在属性“X”
【发布时间】:2019-02-26 20:00:29
【问题描述】:

我有一个来自 Restful API 的设备分页列表,例如名称、序列号等。
我使用 Axios 的 get 方法来获取列表。
看看 Reactjs 中的以下组件:

import * as React from 'react';
import axios from 'axios';

export interface Props{
  url: string;
}
export interface State{
  devices: string[];
  currentUrl: string;
}
class Devices extends React.Component<Props, State>{
    constructor(props: Props){
      super(props);
      this.state = {devices: [], currentUrl: props.url};
      console.log('first log',this.state);
    }
    componentDidMount() {
      axios.get(this.state.currentUrl)
        .then(({data}) =>{
          console.log('Joye Data', data);
          this.setState({devices: data.member})
          console.log('Devices',this.state.devices)
        })
        .catch(function (error){
          console.log('Error of Axios', error);
        })
    }
    render(){
      return(
        <ul>
        {this.state.devices.map(device => <li>{device.name}</li>)}
        </ul>
      );
    }

}

export default Devices;

一切正常,除了 render() 方法捕获以下错误:
'Property 'name' does not exist on type 'string'

据我所知,如果我想用 Reactjs 编译我的代码,我的意思是没有 Typescript,上述代码应该可以正常工作,但是 如何在不违反 TS 的情况下定义属性(React 中的 Props) 约定?



注意:我搜索并发现了相同的问题,但他们的解决方案无法解决问题。

【问题讨论】:

  • 从问题中不清楚data到底是什么。如果device 应该是一个具有name 属性的对象,你为什么将它定义为string
  • @estus data 是一个可选名称,用于获取接收到的数据!我认为某事出错了,那个是“设备”,我没有声明任何“设备”名称。
  • 请具体说明data.member 等于什么。你有矛盾。在某个地方,您希望 device 是一个字符串。在另一个地方,您希望它是一个对象。编译器只是指向它。 我没有声明任何“设备”名称 - 那为什么代码中会出现device.name
  • 没有矛盾。 data 是返回的 JSON,member 是其绑定到 data.element 的元素之一。顺便说一句,正如我提到的,我在接收数据方面没有任何问题(我通过 console.log 进行了检查)。问题是如何通过 TS 映射接收到的数据。关于您的最后一个问题,为什么代码中有device.name,因为访问了设备的name 属性。忘记设备你可以把它改成x 比如:x =&gt; {x.name}.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 应该清楚问题出在哪里,State.devices 被声明为一个字符串数组。您正在映射那些试图访问这些字符串的 name 属性的设备(如错误消息所述)。实际对象实例是否有什么并不重要。更改State 的定义或更改映射设备的方式。

标签: reactjs typescript axios


【解决方案1】:

这是编译器错误。如果代码正常工作,这意味着类型指定不正确,并且这是由 TypeScript 编译器检测到的。

this.state.devices 被键入为具有此行的字符串数组:

devices: string[];

编译器期望 device 在这一行是一个字符串,string 类型是推断出来的,因为 devices 的类型是一个字符串数组:

this.state.devices.map(device => <li>{device.name}</li>);

虽然device 明确用作对象,并且预计具有name 属性。如果device 真的是一个对象,那么类型应该是固定的:

export interface State{
  devices: Array<{ name: string }>;
  currentUrl: string;
}

【讨论】:

    猜你喜欢
    • 2018-03-29
    • 2016-11-14
    • 1970-01-01
    • 2021-12-15
    • 2020-11-24
    • 1970-01-01
    相关资源
    最近更新 更多