简体   繁体   English

谷歌自动完成将 api 放入反应中

[英]google autocomplete places api in react

I'm using google places autocomplete api in my react code.When i kept this code in seperate file and was calling this component in another it was working properly.But when i combined place search input feild with others field in form its not working.Whats the issue when i combined with other field in form?我在我的反应代码中使用谷歌位置自动完成 api。当我将此代码保存在单独的文件中并在另一个文件中调用此组件时,它工作正常。但是当我将位置搜索输入字段与其他字段结合起来时,它不起作用。当我与表单中的其他字段结合时有什么问题?

This code这段代码

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>
 );
}
}

output of this: in seperate file output 这个:在单独的文件中

code after integrating other files(form 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>

Output after adding all code into one file Output 将所有代码添加到一个文件后

Accessing this.state immediately after calling this.setState({...}) is not a guaranteed operation because it's asynchronous read this react FAQ .在调用this.setState({...})后立即访问this.state不是保证操作,因为它是异步读取此反应常见问题解答

So what I will advice you do is pass a callback as second argument to this.setState(newState, callback) , and your callback should contain the whole body of Geocode.fromAddress(...) while you access your state from inside your callback.因此,我建议您将回调作为第二个参数传递给this.setState(newState, callback) ,并且当您从回调内部访问 state 时,您的回调应该包含整个Geocode.fromAddress(...)主体.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Google API - 在 React Native Expo 项目中放置自动完成功能 - Google API - Places autocomplete in React Native Expo Project Google 在 React 组件中放置了自动完成功能 - Google places autocomplete inside a react component Google Places API 自动完成不显示结果 - Google Places API Autocomplete Not Showing Results 回应:Google Places API /地方详情 - React: Google Places API/ Places Details google react-places-autocomplete api 将搜索建议限制在澳大利亚/单个国家/地区 - google react-places-autocomplete api restrict search suggestions to Australia / single country 使用 react-google-maps 和 react-places-autocomplete 时出现“Google Maps JavaScript API 多次”错误 - "Google Maps JavaScript API multiple times" error when using react-google-maps with react-places-autocomplete OnSelect 不适用于 react-Google-places-autocomplete - OnSelect dosnt work with react-Google-places-autocomplete React-google-places-autocomplete street_address 组件不工作? - React-google-places-autocomplete street_address component not working? 有没有办法为 React Google Places AutoComplete 设置初始值? - Is there a way to set the initial value for React Google Places AutoComplete? 从 react-google-places-autocomplete 获取所选项目 - Get selected item from react-google-places-autocomplete
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM