reactjs - 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 数组中。
解决方案
事实证明,这有一个非常愚蠢的解决方案。这些值正在保存到具有小写名称的属性中。我不得不改变
export interface IPropertySearchResults {
Results: IPropertySearchResult[]
}
至
export interface IPropertySearchResults {
results: IPropertySearchResult[]
}
推荐阅读
- python - 在 python 3 中,使用较短的回溯重新引发错误
- google-apps-script - Google Sheet:用相同的名称替换文件
- python - 使用 PrettyTable 打印目录中 Python 文件的详细信息
- c# - DataTable 'Table' 已经属于这个 DataSet - 在一个新的 DataSet 上?
- javascript - Vue.js 无法很好地显示页面
- c - 释放结构
- python - 如何将日期索引转换为熊猫中的字符串列
- python - Travis CI AttributeError:对象没有属性“assertCountEqual”
- java - Java:一个 HashMap,其中包含一个键的 ID 和一个客户端作为值,需要访问客户端的帐户
- vtiger - 如何在 vTiger 中计算