e.results.map不是typescript3中的函数

时间:2019-03-10 18:53:20

标签: typescript

这是我的代码:

Search.tsx

import * as React from 'react';
import axios from 'axios'
import Suggestions from './Suggestions'

const API_KEY:string = "process.env"
const API_URL:string = 'http://127.0.0.1:9001/v1/test'

export class Search extends React.Component{
  state = {
  query: '' as string,
    results : [] as any[]
  }
  search = {
    value: '' as string,
    }
  getInfo = () => {
    axios.post(`${API_URL}/${this.state.query}/`)
      .then(({ data }) => {
        this.setState({
          results: data.data
        })
      })
  }

  handleInputChange = () => {
    this.setState({
      query: this.search.value
    }, () => {
      if (this.state.query && this.state.query.length > 1) {
        if (this.state.query.length % 2 === 0) {
          this.getInfo()
        }
      } else if (!this.state.query) {
      }
    })
  }

  render() {
    return (
      <form>
        <input
          placeholder="Search for..."
          ref={input => this.search = input}
          onChange={this.handleInputChange}
        />
        <Suggestions results={this.state.results} />
      </form>
    )
  }
}

export default Search

和Recommendationion.tsx:

import * as React from 'react';
import { any } from 'prop-types';

export const Suggestions = (props:any) => {
  const options = props.results.map((r: { id: React.Key; name: React.ReactNode; }) => (
    <li key={r.id}>
      {r.name}
    </li>
  ))
  return <ul>{options}</ul>
}

export default Suggestions

但是我收到了Uncaught TypeError:e.results.map不是一个函数:

enter image description here

所以错误在于将我的结果映射到建议中,但是如何纠正呢?

api的结果是:

  

{'data':{'0':'toto','1':'titi'}}

所以我对如何更正此错误以正确将api调用结果映射到建议一无所知。

1 个答案:

答案 0 :(得分:1)

  

{'data':{'0':'toto','1':'titi'}}

您正在访问的data对象不是数组。因此,您不能在对象文字上直接使用Array原型方法(如map)。

您要么需要从API返回一个数组,要么需要更改代码以对对象进行适当的迭代,例如:

for(key in obj) { 
    console.log(obj[key])
}