【问题标题】:Difficulty storing values in const and maintain state of the inputted value ( not props)难以将值存储在 const 中并保持输入值的状态(不是道具)
【发布时间】:2020-06-20 00:34:48
【问题描述】:

作为一个初学者项目,我决定使用google maps API创建一个简单的地方输入,返回距离react项目。我从 youtube 上找到了一个很好的教程,在那里我学到了这一点。但是,当我尝试将 {coordinates.lng} 和 {coordinates.lat} 存储在 const 中以便稍后使用 Google maps API 计算距离时遇到了问题。我尝试创建自己的 add 函数并调用它,但它不起作用。某处我的理解有缺陷,我试图指出它,但我真的不明白。 如何存储 {coordinates.lat} 和 {coordinates.lng} 的值?

import React from "react";
import PlacesAutocomplete, {
  geocodeByAddress,
  getLatLng
} from "react-places-autocomplete";

export default function Itinerary() {
  const [address, setAddress] = React.useState("");
  const [coordinates, setCoordinates] = React.useState({
    lat: null,
    lng: null
  });

  const add = (coordinates) => {
  const Latitude= {coordinates.lat};
  console.log(Latitude);
  };

  const handleSelect = async value => {
    const results = await geocodeByAddress(value);
    const latLng = await getLatLng(results[0]);
    setAddress(value);
    setCoordinates(latLng);
  };

  return (
    <div className="container">
    <div className="row">
    <div className="col-md-6 mt-5 mx-auto">
      <PlacesAutocomplete
        value={address}
        onChange={setAddress}
        onSelect={handleSelect}
       >
        {({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
          <div>
            <h1>Latitude: **{coordinates.lat}**</h1>
            <h1>Longitude: **{coordinates.lng}**</h1>
            <h1> {console.log({coordinates.lng}}</h1>
            <input size="50" height="40"{...getInputProps({ placeholder: "Type address" })} />
            {add(coordinates)}
            <div>
              {loading ? <div>...loading</div> : null}

              {suggestions.map(suggestion => {
                const style = {
                  backgroundColor: suggestion.active ? "#41b6e6" : "#fff"
                };

                return (
                  <div {...getSuggestionItemProps(suggestion, { style })}>
                    {suggestion.description}
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </PlacesAutocomplete>
    </div>
    </div>
    </div>
  );
}

【问题讨论】:

    标签: javascript node.js reactjs jsx


    【解决方案1】:

    要定义位置的架构,

    place:{
          name: 'NameOfThePlace',
          location:{
              type:'Point',
              coordinates:[long,lat]
             }
           }
    

    这是一个位置的对象,其中,您的纬度和经度是数组的形式。创建地点对象后,如果您选择多个地点,也可以将它们放入地点数组中。 这种格式还支持mongodb结构的保存和检索。

    【讨论】:

    • 我碰巧正在使用带有 sequelize 的 sql 作为后端。有没有办法将它存储在二维数组中?
    • 我认为 sql 使用数据类型处理它。请看这个例子link
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多