当前在我的React版本16.13.1的项目上使用TypeScript。
尝试从此@react-google-maps/api获取自动完成功能,但示例在类组件中,而我使用的是功能钩子。
任何想法我的代码有什么问题吗?这是我从图书馆得到的一个例子。
中的代码示例class MyMapWithAutocomplete extends Component {
constructor (props) {
super(props)
this.autocomplete = null
this.onLoad = this.onLoad.bind(this)
this.onPlaceChanged = this.onPlaceChanged.bind(this)
}
onLoad (autocomplete) {
console.log('autocomplete: ', autocomplete)
this.autocomplete = autocomplete
}
onPlaceChanged () {
if (this.autocomplete !== null) {
console.log(this.autocomplete.getPlace())
} else {
console.log('Autocomplete is not loaded yet!')
}
}
render () {
return (
<ScriptLoaded>
<GoogleMap
id="searchbox-example"
mapContainerStyle={mapContainerStyle}
zoom={2.5}
center={center}
>
<Autocomplete
onLoad={this.onLoad}
onPlaceChanged={this.onPlaceChanged}
>
<input
type="text"
placeholder="Customized your placeholder"
/>
</Autocomplete>
</GoogleMap>
</ScriptLoaded>
)
}
}
我目前有什么
function GoogleMaps({ data = [], center, withAutocomplete = false }: MapProps) {
const [setAutocomplete, autocomplete] = useState() as any
const { isLoaded, loadError } = useLoadScript({
googleMapsApiKey: 'xxx',
libraries: ['places']
})
const onLoad = useCallback((props) => {
setAutocomplete(props)
}, [])
const onPlaceChanged = () => {
console.log('place', onLoad)
if (autocomplete !== null) {
console.log('test', autocomplete.getPlace())
}
}
const renderMap = () => {
return (
<GoogleMap
options={{
mapTypeControl: false,
streetViewControl: false
}}
mapContainerStyle={{ height: '600px' }}
center={center}
zoom={12}>
{data.length > 0 &&
data.map((d, idx) => {
const position = { lat: d.lat, lng: d.lng }
return <Marker position={position} key={`marker-${idx}`} />
})}
{withAutocomplete && (
<Autocomplete onLoad={onLoad} onPlaceChanged={onPlaceChanged}>
<TextField variant="outlined" />
</Autocomplete>
)}
</GoogleMap>
)
}
if (loadError) {
return <div>Map cannot be loaded right now, sorry.</div>
}
return isLoaded ? renderMap() : <CircularProgress />
}
运行此程序时出现错误。 TypeError:setAutocomplete不是函数
答案 0 :(得分:3)
您在useState
中向后调用数组项:
const [setAutocomplete, autocomplete] = useState() as any
您想要这个:
const [autocomplete, setAutocomplete] = useState() as any
数组中的第一项是保存状态值的变量,第二项是React用于维护状态值的函数。在您当前的代码中,setAutoComplete
不是函数,而autoComplete
是函数。