Переменная React не обновляется - PullRequest
0 голосов
/ 08 апреля 2019

Я пытался рассчитать общее время в пути между несколькими местами с помощью API Карт Google. Но при попытке доступа к переменной total_duration с вышеприведенной информацией мне ничего не показывается на консоли.

const responses = [];
    let total_duration = 0;
    for(let i = 0 ; i < origins.length ; i++){
      const matrix = new google.maps.DistanceMatrixService();
      matrix.getDistanceMatrix({
        origins: origins[i],
        destinations: destinations[i],
        travelMode: google.maps.TravelMode.DRIVING,
      }, 
      function(response, status){
        responses.push(response);
      });
    }
    console.log(responses);
    for(let i = 0 ; i < responses.length ; i++){
      total_duration += responses[i].rows[0].elements[0].duration.value;
      console.log(responses[i])
    }
    console.log(total_duration);

Первый журнал консоли показывает все результаты для каждой пары мест.

[
  {
    "rows": [
      {
        "elements": [
          {
            "distance": {
              "text": "1.2 km",
              "value": 1161
            },
            "duration": {
              "text": "3 mins",
              "value": 169
            },
            "status": "OK"
          }
        ]
      }
    ],
    "originAddresses": [
      "3670 SW 3rd St, Miami, FL 33135, USA"
    ],
    "destinationAddresses": [
      "3911 SW 2nd Terrace, Coral Gables, FL 33134, USA"
    ]
  },
  {
    "rows": [
      {
        "elements": [
          {
            "distance": {
              "text": "1.5 km",
              "value": 1473
            },
            "duration": {
              "text": "4 mins",
              "value": 226
            },
            "status": "OK"
          }
        ]
      }
    ],
    "originAddresses": [
      "3911 SW 2nd Terrace, Coral Gables, FL 33134, USA"
    ],
    "destinationAddresses": [
      "4490 SW 5th Terrace, Coral Gables, FL 33134, USA"
    ]
  }
]

Но другие журналы консоли не показывают мне нужную мне информацию. Можете ли вы помочь мне с этой ошибкой? Заранее спасибо.

Теперь, когда я пытаюсь обновить state в функции getTimes, мое состояние не обновляется. Время всегда 0.


import React, {Component} from 'react';

class HomePage extends Component {

  constructor(props) {
    super(props);

    this.state = {
      time: 0,
      places: [
        {latitude: some_data, longitude: some_data},
        {latitude: some_data, longitude: some_data}
      ]
    };
  }

  componentDidMount(){}

  getTimes = () => {
    const origins = [], destinations = [];
    for(let i = 0 ; i < this.state.places.length - 1 ; i++){
      origins.push([new google.maps.LatLng(this.state.places[i].latitude, 
        this.state.places[i].longitude)]);
      destinations.push([new google.maps.LatLng(this.state.places[i + 1].latitude, 
        this.state.places[i + 1].longitude)]);  
    }
    let total_duration = 0;
    for(let i = 0 ; i < origins.length ; i++){
      const matrix = new google.maps.DistanceMatrixService();
      matrix.getDistanceMatrix({
        origins: origins[i],
        destinations: destinations[i],
        travelMode: google.maps.TravelMode.DRIVING,
      }, 
      (response, status) => {
        total_duration += response.rows[0].elements[0].duration.value;
        console.log(total_duration);
        this.setState({time: total_duration});
      });
    }
    console.log(this.state.time);    
  }

  render() {
    const {time} = this.state;
    return (
      <h1>{time}</h1>
    );
  }
}

1 Ответ

1 голос
/ 08 апреля 2019
 this.setState(state => {
  const newTime = state.time + total_duration
  return { count: newTime }
}, () => {
  console.log(this.state.time);  
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...