首页 > 解决方案 > 看不到通过数据映射的结果

问题描述

结果,无法通过我从谷歌距离 API 获得的数据查看映射结果。

import React, { Component } from 'react';

import { connect } from 'react-redux';

import SearchComponent from './search_component';

import _ from 'lodash';

class App extends Component {

constructor(props) {
    super(props);
    this.state = {
        distances: ''
    }
}

componentWillReceiveProps(newProps) {
    if(newProps.Distances) {
        this.setState({
                          distances: newProps.Distances
                      })
    }
}

renderDistancesList() {
    if(_.isObject(this.state.distances)){
        let d = this.state.distances;
        console.log('this.state.distances ', d);
            return (
            <div>
                <h4>Distsances:</h4>
                {
                    _.map(d, (key, value) => {
                        return <li key={key}>{key}</li>
                    })
                }
            </div>
            )
    } else {
  return (<div>Loading data...</div>)
}
}

render() {
    return (
    <div>
        <div>HelloFrom App</div>
        <SearchComponent/>
        {this.renderDistancesList()}
    </div>
    )
}
}

function mapStateToProps({ Distances }) {
    return { Distances }
}

export default connect(mapStateToProps, null)(App);

标签: reactjsredux

解决方案


我通常使用 es6 的 map 函数,而不是 lodash 或其他东西,但实际上我会做什么

renderDistancesList() {
    if(_.isObject(this.state.distances)){
        let d = this.state.distances;
        console.log('this.state.distances ', d);
            return (
            <div>
                <h4>Distsances:</h4>
                {
                   this.getData(d)
                }
            </div>
            )
    } else {
  return (<div>Loading data...</div>)
}
}


  getData(d){
    return d.map((res,key)=>{
          return <li key={key}>{key}</li>
    })

推荐阅读