首页 > 解决方案 > React 组件中的属性始终未定义

问题描述

我有一个简单的 React 组件,它应该从 api 检索一些对象并将它们显示在屏幕上。问题是,保存我的数据的属性似乎总是​​有一个未定义的值。在 C# 中,我有一个 Property 类:

public class Property
{
    public int PropertyID { get; set; }
    public string Name { get; set; }
}

我的组件的父级从 api 获取这些列表并将它们作为道具传递。这是我的组件:

export interface IPropertySearchResult {
    PropertyID: number,
    Name: string
}

export interface IPropertySearchResults {
    Results: IPropertySearchResult[]
}

export interface IPropertyWindowProps {
    Properties: IPropertySearchResults
}

export interface IPropertyWindowState {
}

export class PropertyWindow extends React.Component<IPropertyWindowProps, 
IPropertyWindowState> {
    constructor(props: IPropertyWindowProps) {
    super(props);
    }

render() {
    return (
        <div >
            <ul>
                {
                    this.props.Properties && this.props.Properties.Results ?                        
                        this.props.Properties.Results.map((p: IPropertySearchResult, idx: number) =>
                            <li key={idx}> <PropertyEditor Property={p} /> </li>)                        
                        : 'properties null'
                }
            </ul>
        </div>
    );
}

}

如下图所示,this.props.Properties 包含我需要的对象,但由于某种原因,this.props.Properties.Results 始终标记为未定义。

截屏.

更新

我认为这个问题与我读取数据的方式有关。我有我的控制器:

[HttpGet("Search")]
public IActionResult GetProperties()
{
    var props = new Property[]
    {
        new Property(){PropertyID=1, Name="default1"},
        new Property(){PropertyID=2, Name="default2"},
        new Property(){PropertyID=3, Name="default3"},
        };

        return Ok(new { Properties = props });
    }
}

及其客户:

export class PropertyReader {
    public static search(): Promise<IPropertySearchResults> {
        return new Promise<IPropertySearchResults>((resolve, reject) => {
            axios.get(`api/Settings/Search`)
                .then(res => {
                    resolve(res.data);
                });
        });
    }
}

然后我的组件的父级调用客户端:

    componentDidMount() {
        PropertyReader.search()
            .then(p => this.setState({ properties: p }));
    }

出于某种原因,它正在创建一个 IPropertySearchResults 并将数据放入动态添加的数组中,而不是放入 Results 数组中。

标签: reactjstypescript

解决方案


事实证明,这有一个非常愚蠢的解决方案。这些值正在保存到具有小写名称的属性中。我不得不改变

export interface IPropertySearchResults {
    Results: IPropertySearchResult[]
}

export interface IPropertySearchResults {
    results: IPropertySearchResult[]
}

推荐阅读