求助:如何将指定React类组件正确转换为函数组件?
React类组件转函数组件正确方案
核心修正点
- 函数组件不存在类组件的
this上下文,无需使用this.setState,直接调用useState返回的对应状态更新函数即可 - 函数组件内部的自定义方法需要用
const声明,不能沿用类组件的赋值写法
import { useState } from 'react'; const Location = () => { const [address, setAddress] = useState(''); const [showingInfoWindow, setShowingInfoWindow] = useState(false); const [activeMarker, setActiveMarker] = useState({}); const [selectedPlace, setSelectedPlace] = useState({}); const [mapCenter, setMapCenter] = useState({ lat: 49.2827291, lng: -123.1207375 }); const handleChange = (address) => { setAddress(address); }; const handleSelect = (address) => { setAddress(address); geocodeByAddress(address) .then((results) => getLatLng(results[0])) .then((latLng) => { console.log('Success', latLng); // 更新中心坐标状态 setAddress(address); setMapCenter(latLng); }) .catch((error) => console.error('Error', error)); }; // 此处补充原有组件的渲染逻辑即可 return ( // 原有渲染内容 ); }; export default Location;
内容的提问来源于stack exchange,提问作者user13423237
相关产品推荐
相关产品推荐

