javascript - 未捕获( promise 中)TypeError : this. state.[prop].map 不是函数

标签 javascript reactjs typescript

我是 React 新手。我正在 Visual Studio 2017 中构建一个组件,用户在其中输入一些文本,然后根据该文本从数据库中获取值并显示在 div 中。下面是我正在使用的类和接口(interface)。

interface ISearchForm {
  suggestionList: ISuggestionList[];
  searchText: string;
}

interface ISuggestionList {
  queryDetails: IQueryDetails;
  data: IDataForUsers[];
}

interface IQueryDetails {
  search: string;
  returncount: number;
  skip: number;
  top: number;
}

interface IDataForUsers {
  users: IUsers[];
}

interface IUsers {
  profileId: string;
  firstName: string; 
  middleName: string;
  lastName: string;
}  

我之所以有如此复杂的结构,是因为 API 返回一个复杂的 JSON,如下所示:

"querydetails": {
  "search": "sample string 1",
  "returncount": 2,
  "skip": 3,
  "top": 4
},
"data": {
  "users": [{
    "profileId": "sample string 1",
    "firstName": "sample string 2", //I want to retrieve array of this key for every user
    "middleName": "sample string 3",
    "lastName": "sample string 4",
  }, {
    "profileId": "sample string 1",
    "firstName": "sample string 2",
    "middleName": "sample string 3",
    "lastName": "sample string 4",
  }]
}

下面是我的类(class)。现在整个代码都在 typescript 中:

import * as React from 'react';
import { RouteComponentProps } from 'react-router';
export class Search extends React.Component<RouteComponentProps<{}>, 
ISearchForm> {
  constructor() {
    super();
    this.state = { suggestionList: [], searchText: '' };
    this.handleSerachTextChange = this.handleSerachTextChange.bind(this);
  }//Some more code after this
}

在文本更改事件中,我进行 API 调用并将响应分配给 suggestionList[]

handleSerachTextChange(e: any) {
    this.setState({ searchText: e.target.value });
    this.setState({ suggestionList: [] });
    if (e.target.value == '') {}
    else {
        var propsForAPI = { search: e.target.value, skip: 0, top: 10 };
        var jsonData = JSON.stringify(propsForAPI);

        fetch('apiURL', {
            method: 'POST',
            headers: {
                'Content-type': 'application/json'
            },
            body: jsonData
        })
        .then(response => response.json() as Promise<ISuggestionList[]>)
        .then(data => {
             this.setState({ suggestionList: data });
        });
    }
}

这就是我的渲染方法的样子。当我尝试使用 this.state.suggestionList.map() 时,它在运行时出现错误。

我创建内部 div 的原因是 this video .

public render() {
    return <div>
        <input type="text" value={this.state.searchText} onChange={this.handleSerachTextChange} />
        <div>
            {
                this.state.suggestionList.map((dataArray) => {
                    <div>
                        {
                            dataArray.data.map((usersList) => {
                                <div>
                                    {
                                        usersList.users.map((userArray) => {
                                            <div>
                                                {
                                                    userArray.firstName
                                                }
                                            </div>
                                        })
                                    }
                                </div>
                            })
                        }
                    </div>
                })
            }
        </div>
    </div>
}

有人可以告诉我为什么会收到此错误吗?或者我如何检索所有用户的 firstName 列表?我不想更改从 API 调用中获得的响应。任何帮助,将不胜感激。

最佳答案

在您的代码中,您期望 JSON 结果的类型为 ISuggestionList[]。但这根本不匹配。。在尝试其他操作之前,您需要修复您的类型。

  • JSON 结果的类型为 ISuggestionList,而不是该类型的数组
  • 同样,ISuggestionList 中的 data 也不是数组,而是具有 users 属性的对象。所以它是 IDataForUsers (同样没有数组)。
  • 由于您的 JSON 只是一个 ISuggestionList,因此 ISearchForm 也不应该包含多个 ISuggestionList 元素。

一旦解决了这个问题,您应该会收到编译器错误,这些错误应该指导您正确使用对象。然后你还会意识到你不能在 state.suggestionList 上使用 map,因为它不是一个数组。

此外,您确实应该调整类型的命名。您应该对代表单个事物的事物使用单数名称,并且当它不是实际的事物列表时,不要将其称为 List

关于javascript - 未捕获( promise 中)TypeError : this. state.[prop].map 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49296144/

相关文章:

javascript - 使用react-date-picker时隐藏移动设备上的 native 键盘

javascript - 与 Material ui react 时弹出窗口中出现错误

reactjs - 无法使用 create-react-app 创建应用程序

javascript - 使用 private 时,Typescript 类无法访问

javascript - Typescript 通过多个关键字过滤具有字符串数组的对象数组

javascript - 仅在解析异步函数后如何使嵌套循环继续,或者如何将 ".then"扩展到范围之外

javascript - 使 parseFloat 将带逗号的变量转换为数字

javascript - 验证电子邮件时无法阻止表单提交

javascript - 如何在 Node 中转义 shell 命令的字符串?

javascript - 使用 TempleteUrl 获取 Highcharts 工具提示以返回 Angular Directive(指令)?