You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何将指定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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 12:12:04