获取对象作为React子错误无效

时间:2018-07-21 20:46:39

标签: reactjs fetch-api setstate

我正在尝试向服务器提出获取请求,并将响应json设置为组件的状态。 我收到此错误

Objects are not valid as a React child (found: object with keys {description, 
    id, matched_substrings, place_id, reference, structured_formatting, terms, types}). If you meant to render a collection of children, use an array instead.
    in li (at Search.js:25)
    in ul (at Search.js:30)
    in div (at Search.js:28)
    in Search (at index.js:8)

这是我的代码-

import React from 'react'
import { ReactDOM } from "react-dom";

export default class Search extends React.Component {
constructor(props) {
    super(props);
    this.state = { 
        places: []
     }
     this.handleUserInput = this.handleUserInput.bind(this)
}
handleUserInput(e) {
    var searchInput = e.target.value;
    var url = '/searchLocation/autocomplete?text=' + (searchInput)

    if (searchInput.length > 2) {
        fetch(url).then(function(response) {return response.json()})
        .then((responseJson) => this.setState({places: responseJson["predictions"]}));    
        //.then( responseJson => console.log(responseJson["predictions"]))
    }
}
render() {
    const placeList = this.state.places.map(place => 
        {
            return <li>{place}</li>
        });
    return (
        <div>
            <input onChange={this.handleUserInput} type="text" id="PlaceSearch" />
            <ul>
                { placeList }
            </ul>    
        </div>  
    );      
}
}

我通过谷歌搜索发现了类似的错误,但没有帮助。

非常感谢您的帮助

2 个答案:

答案 0 :(得分:3)

此问题是您正在尝试渲染place,我认为它是li内部的对象。

您需要选择要呈现的属性

例如:

return <li>{place.id}</li>

答案 1 :(得分:0)

我认为您缺少括号;

>>