【发布时间】:2021-10-14 17:53:37
【问题描述】:
我正在尝试将类组件转换为函数组件,但没有成功。这是我要转换的类组件:
constructor(props) {
super(props);
this.state = {
address: '',
showingInfoWindow: false,
activeMarker: {},
selectedPlace: {},
mapCenter: {
lat: 49.2827291,
lng: -123.1207375,
},
};
}
handleChange = (address) => {
this.setState({ address });
};
handleSelect = (address) => {
this.setState({ address });
geocodeByAddress(address)
.then((results) => getLatLng(results[0]))
.then((latLng) => {
console.log('Success', latLng);
// update center state
this.setState({ address });
this.setState({ mapCenter: latLng });
})
.catch((error) => console.error('Error', error));
};
这是我失败的尝试:
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})
handleChange = (address) => {
this.setState({ address });
};
handleSelect = (address) => {
this.setState({ address });
geocodeByAddress(address)
.then((results) => getLatLng(results[0]))
.then((latLng) => {
console.log('Success', latLng);
// update center state
this.setState({ address });
this.setState({ mapCenter: latLng });
})
.catch((error) => console.error('Error', error));
};
return (
【问题讨论】:
-
这甚至不是一个完整的类组件。您能否分享完整的示例以及您尝试转换为功能组件的尝试,即使它不起作用,也可以。尝试还包括有关不工作和/或您遇到的任何错误的详细信息。
-
我没有任何错误也可以显示我的尝试,请稍等,我也可以不发送完整的代码,这是我唯一需要转换的部分,我可以做剩下的谢谢!
-
希望你能理解
-
对不起,我说我还很新
-
将
this.setState({ address });转换为setAddress(address)以便类型匹配。对其他状态和更新程序执行类似操作。
标签: javascript reactjs react-hooks