简体   繁体   English

有没有办法为 React Google Places AutoComplete 设置初始值?

[英]Is there a way to set the initial value for React Google Places AutoComplete?

Using this library -https://tintef.github.io/react-google-places-autocomplete/docs/ -I have -使用这个库 -https://tintef.github.io/react-google-places-autocomplete/docs/ -我有 -

  <GooglePlacesAutocomplete
      apiKey={'someKey'}
      autocompletionRequest={{
          componentRestrictions: {
              country: ['uk']
          }
      }}
      selectProps={{
          value: address,
          onChange: (o) => {
              let placeId = o["value"]["place_id"];
              setAddress(o);
              formik.setFieldValue("googlePlaceId", placeId);
          }
      }}
  />

What do I need to pass as the value of "address" for there to be an initial value?我需要传递什么作为“地址”的值才能有一个初始值?

I've tried {label: "some address", place_id: "ChIJNYiUp8ROeEgRikq4Ws76OpU"} and passing the object returned by using the utility geocodeByPlaceId.我试过 {label: "some address", place_id: "ChIJNYiUp8ROeEgRikq4Ws76OpU"} 并传递使用实用程序 geocodeByPlaceId 返回的对象。 The former works in so far has it shows the label in the input field upon initialisation but it appears broken.到目前为止,前者在初始化时在输入字段中显示标签,但它似乎已损坏。 For example when I try and delete the value with backspace my react app crashes with this error in the console -例如,当我尝试使用退格键删除值时,我的 React 应用程序因控制台中的此错误而崩溃 -

Uncaught TypeError: Cannot read property 'place_id' of undefined
    at Object.getOptionValue (index.es.js:30)
    at cr (index.es.js:30)
    at eval (index.es.js:30)
    at Array.some (<anonymous>)
    at lr (index.es.js:30)
    at or (index.es.js:30)
    at eval (index.es.js:30)
    at Array.map (<anonymous>)
    at rr (index.es.js:30)
    at eval (index.es.js:30)

Annoyingly the documentation for this library refers one to the documentation for another, react-select.令人讨厌的是,这个库的文档引用了另一个,react-select 的文档。

This is now my how my component looks -这就是我的组件的外观 -

                            <GooglePlacesAutocomplete
                                apiKey={''}
                                autocompletionRequest={{
                                    componentRestrictions: {
                                        country: ['uk']
                                    }
                                }}
                                selectProps={{
                                    defaultInputValue: formik.status["addressLabel"],
                                    isClearable: true,
                                    value: address,
                                    onChange: (o) => {
                                        let placeId = "";
                                        if(o){
                                            placeId = o["value"]["place_id"];
                                        }
                                        setAddress(o);
                                        formik.setFieldValue("googlePlaceId",placeId);
                                    }
                                }}
                            />

So in a higher component I have -所以在更高的组件中,我有 -

const [address, setAddress] = useState();

And the default initial value is set like this (using formik) -并且默认初始值是这样设置的(使用 formik) -

                            <Formik
                                initialValues={initialValues}
                                validationSchema={validationSchema}
                                // validationSchema={{}}
                                onSubmit={(values, actions) => {
                                    actions.setSubmitting(false);
                                    submitHandler(values, actions)
                                }}
                                initialStatus={{
                                    addressLabel: addressLabel
                                }}
                            >
                                {
                                    formik => {
                                        return (
                                            <Form formik={formik} {...formProps} />
                                        )
                                    }
                                }
                            </Formik>

This is best achieved following the docs of React-Select as suggested by the creator.这最好按照创建者的建议按照 React-Select 的文档来实现。 But to achive what you want to do, you'll need React State.但是要实现你想做的事,你需要 React State。

import { useState, useEffect } from "react";
import GooglePlacesAutocomplete from "react-google-places-autocomplete";

const Places=()=>{
  const [data, setData] = useState("");
//our default data

useEffect(() => {
    data === ""
      ? setData("")
      : setData(data.label);
  }, [data]);
// updating our default data

return(
 <GooglePlacesAutocomplete
                  apiKey={process.env.REACT_APP_MAP_API_KEY}
                  autocompletionRequest={{
                    componentRestrictions: {
                      country: ["ng"], //to set the specific country
                    },
                  }}
                  selectProps={{
                    defaultInputValue: data, //set default value
                    onChange: setData,  //save the value gotten from google
                    placeholder: "Start Destination",
                    styles: {
                      input: (provided) => ({
                        ...provided,
                        color: "#222222",
                      }),
                      option: (provided) => ({
                        ...provided,
                        color: "#222222",
                      }),
                      singleValue: (provided) => ({
                        ...provided,
                        color: "#222222",
                      }),
                    },
                  }}
                  onLoadFailed={(error) => {
                   console.log(error);
                  }}
                />
)
}

export default Places;

We use useEffect to update the defualt value we set on condition that we are getting an actual value.我们使用 useEffect 更新我们设置的默认值,条件是我们获得了实际值。 If we're not getting actual value, we're not saving it.如果我们没有获得实际价值,我们就不会保存它。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM