地图功能值未显示

时间:2018-12-31 08:00:39

标签: javascript reactjs

console.log中,正在显示api提取的数据,但在浏览器中 仅显示白屏。在地图功能中必须更新状态功能

import React, { Component } from 'react';;
import * as algoliasearch from "algoliasearch";
class App extends React.Component {

  constructor() {
    super();
    this.state = {
      data: { hits: [] }
    }
    // set data to string instead of an array  
  }

  componentDidMount() {
    this.getData();
  }

  getData() {
    var client = algoliasearch('api-id', 'apikey');
    var index = client.initIndex('');
    //index.search({ query:""}, function(data){  console.log(data) })    
    //index.search({ query:""}, function(data){  console.log("DataRecib=ved. First check this") }) 

    index.search({
      query: "",
      attributesToRetrieve: ['ItemRate', 'Color'],
      hitsPerPage: 50,
    },
    function searchDone(error, data) {
      console.log(data.hits)
    });
  }

  render() {
    return (
      <div id="root">
        {
          this.state.data.hits.map(function (data, index) {
            return
            <h1>{this.setState.data.ItemRate}<br />{data.Color}</h1> >            
            })}
      </div>
    );
  }
}
//render(<App />, document.getElementById('app')); 
export default App;

2 个答案:

答案 0 :(得分:2)

错误对--

答案 1 :(得分:0)

每个this.setState都会触发一个render()呼叫。如果您在渲染方法中setState,将进入无限循环。

您要在this.state.data.hits函数中更新getData(),然后可以像这样显示数据:

this.state.data.hits.map(data =>
  <h1>{data.Color}</h1>
)

例如,如果console.log(data.hits)注销正确的数据,则可以:

this.setState({
  data: {
    hits: data.hits
  }
})

编辑:

使用您提供的代码,应该像这样:'

getData = () => {
  var client = algoliasearch('A5WV4Z1P6I', '9bc843cb2d00100efcf398f4890e1905');
  var index = client.initIndex('dev_twinning');
  //index.search({ query:""}, function(data){ console.log(data) }) 
  // index.search({ query:""}, function(data){ console.log("Data Recib=ved. First check this") }) 
  index.search({
    query: "",
    attributesToRetrieve: ['ItemRate', 'Color'],
    hitsPerPage: 50,
  }, searchDone = (error, data) => {
    this.setState({
      data: {
        hits: data.hits
      }
    })
    console.log(data.hits)
  })
}