繁体   English   中英

获取搜索引擎结果页面的地图未定义错误

[英]Getting a map undefined error for search engine results page

当它转到我的建议方法时,我不断收到此错误。

未捕获的类型错误:无法读取建议第 4 行中未定义的属性“地图”

谁能帮我弄清楚原因吗?

我是新手,请原谅我的无知。

import React from 'react';

const Suggestions = props => {
  const options = props.results.map (r => (
    <li key={r.id}>
      {r.name}
    </li>
  ));
  return <ul className="ul-list">{options}</ul>;
};

export default Suggestions;

这是搜索栏的其余代码。 我删除了 api 信息,但它在那里。

import React, {Component} from 'react';
import axios from 'axios';
import Suggestions from '../SearchBbg/suggestions';
import '../../style/searchbar.scss';

const API_KEY = '';
const API_URL = '';

class Search extends Component {
  state = {
    query: '',
    results: [],
  };

  getInfo = () => {
    axios
      .get (`${API_URL}?api_key=${API_KEY}&prefix=${this.state.query}&limit=7`)
      .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
          className="search-bar"
          placeholder="Search for..."
          ref={input => (this.search = input)}
          onChange={this.handleInputChange}
        />
        <Suggestions results={this.state.results} />
      </form>
    );
  }
}

export default Search;

我相信你已经在你的axios调用data属性中被破坏了。 这可能是您对props.results undefinedprops.results

因此,请尝试以下操作:

getInfo = () => {
    axios
      .get(`${API_URL}?api_key=${API_KEY}&prefix=${this.state.query}&limit=7`)
      .then(({data}) => { // here already destructured
        this.setState ({
          results: data // removed => .data,
        });
      });
};

另外还值得在使用.map()之前检查nullundefined值,如props.results && props.results.map() .map() ,所以你可以使用 like 来确保:

const Suggestions = props => {
  const options = props.results && props.results.map (r => (
    <li key={r.id}>
      {r.name}
    </li>
  ));
  return <ul className="ul-list">{options}</ul>;
};

我希望这能澄清!

您的结果数组未定义。 检查您是否将结果作为道具传递给建议,以及结果数组是否未定义。

编辑:

似乎您正在为结果分配一些 null 或 undefined ,发生这种情况的唯一方法是在您的 api 响应中。 检查您是否正确解析服务器响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM