开发者问题收集

谷歌自动完成 API 在 React 中

2020-07-28
1067

我在我的 React 代码中使用了 Google Places 自动完成 API。当我将此代码保存在单独的文件中并在另一个文件中调用此组件时,它可以正常工作。但是当我将地点搜索输入字段与表单中的其他字段组合时,它不起作用。当我与表单中的其他字段组合时出现了什么问题?

此代码

import React from "react";
/* global google */

class SearchBar extends React.Component {
constructor(props) {
 super(props);
 this.autocompleteInput = React.createRef();
 this.autocomplete = null;
 this.handlePlaceChanged = this.handlePlaceChanged.bind(this);}

componentDidMount() {
 this.autocomplete = new google.maps.places.Autocomplete(this.autocompleteInput.current,
    {"types": ["geocode"]});

 this.autocomplete.addListener('place_changed', this.handlePlaceChanged);
}

handlePlaceChanged(){
 const place = this.autocomplete.getPlace();
 this.props.onPlaceLoaded(place);
}

render() {
 return (
    <input ref={this.autocompleteInput}  id="autocomplete" placeholder="Enter your address"
     type="text"></input>
 );
}
}

此代码的输出: 在单独的文件中

集成其他文件后的代码(表单输入)

import React from "react";
import Geocode from "react-geocode";
import DatePicker from 'react-datepicker';
import Scrollbars from 'react-custom-scrollbars';
require('react-datepicker/dist/react-datepicker.css');

// set Google Maps Geocoding API for purposes of quota management. Its optional but 
recommended.
Geocode.setApiKey("API_KEY");
/* global google */

export default class Checkout extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    locality: "",
    lat : 0,
    lng: 0,
    otherState...
  }
  this.autocompleteInput = React.createRef();
  this.autocomplete = null;
  this.handlePlaceChanged = this.handlePlaceChanged.bind(this);
}

componentDidMount() {
  this.autocomplete = new google.maps.places.Autocomplete(this.autocompleteInput.current,
    {"types": ["geocode"]});

  this.autocomplete.addListener('place_changed', this.handlePlaceChanged);

}

handlePlaceChanged(){
  const place = this.autocomplete.getPlace().formatted_address;
  //this.props.onPlaceLoaded(place);
  this.setState({locality: place})
  Geocode.fromAddress(this.state.locality).then(
  response => {
    const { lat, lng } = response.results[0].geometry.location;
    console.log(lat, lng);
    this.setState({
        lat: lat,
        lng: lng
    })
  },
  error => {
    console.error(error);
  }
);
}
render() {
let publicUrl = process.env.PUBLIC_URL+'/'
let items = JSON.parse(localStorage.getItem("items"));

return (
  
// checkout page
    <div className="contact-area pd-top-20 pd-bottom-65">
      <div className="container">
            <form className="contact-form-wrap contact-form-bg" onSubmit={e => 
             this.handleSubmit(e)}>
              <h4>Checkout</h4>
                ...other input feilds
               <div className="row">
            
               <div className="col-10 col-md-11" >
               <h4>Select/Add new address</h4>

               <div className="rld-single-input">
                <label>Enter new address</label>
                <input className="mb-2" ref={this.autocompleteInput}  id="autocomplete" 
                placeholder="Enter Locality"
                type="text"></input>
                <input placeholder="Enter flat no./Bilding name" onChange={(e) => 
                 this.handleLandmark(e)}/>
                
                  </div>
              </div>
            </div>
          </div>            
         </form>

将所有代码添加到一个文件后的输出

1个回答

在调用 this.setState({...}) 之后立即访问 this.state 并不是一个有保证的操作,因为它是异步的 阅读此 React FAQ

因此,我建议您将回调作为第二个参数传递给 this.setState(newState, callback) ,并且当您从回调内部访问状态时,回调应包含 Geocode.fromAddress(...) 的整个主体。

calebpitan
2020-07-28