react,使用hook,导航栏如何自动获取当前定位城市名称?

在使用的react版本如下:

img


已写的代码如下:

import React, { useEffect, state } from 'react'
import { GlobalOutline, DownOutline, SearchOutline } from 'antd-mobile-icons';
import { useNavigate } from 'react-router-dom'
import './style.css'
import axios from 'axios'
import { getCurrentCity } from '../../../utils'
function IndexSearch() {
// export default class Myindexsearch extends React.Component {
    const navigate = useNavigate()
    state = {
      // 当前城市名称
      curCityName: '上海'
    }
    // 通过 IP 定位获取到当前城市名称
    const curCity = new window.BMapGL.LocalCity()
    curCity.get(res => {
      // console.log('当前城市信息:', res)
      const result = axios.get(
        `http://localhost:8080/area/info?name=${res.name}`
      )
      // console.log(result)
      this.setState({
        curCityName: result.data.body.label
      })
    })
    useEffect(() => {
      const curCity = getCurrentCity()
      this.setState({
        curCityName: curCity.label,
      });
    }, []);
  // render() {
    return (
      <div className='search-box-indexsearch'>
        <div className='search'>
          <div className='location' onClick={()=>{navigate("/citylist")}}>
            <span className='name'>{this.state.curCityName} </span>
            {/* <span className='name'>广州 </span> */}
            <i className='icon-arrow'><DownOutline /></i>
          </div>
          <div className='form' onClick={()=>{navigate("/search")}}>
            <i className='icon-search'><SearchOutline /></i>
            <span className='text'>请输入小区或地址</span>
          </div>
        </div>
        <i className='icon-map' onClick={()=>{navigate("/map")}}><GlobalOutline /></i>
      </div>
    )
  // }
}
export default IndexSearch
 

chrome浏览器界面报错如下:

img

测试过接口地址能成功获取到当前定位城市信息以及当前定位城市名称
目前效果如下:

img

希望实现效果——页面每次加载时都自动获取当前定位城市名称并显示,如下所示:

img

请问代码出了什么问题?如何修改?

不适用class方式的话,新版react你应该将 componentDidMount替换成 useEffect

useEffect(() => {
    const curCity = getCurrentCity();
    this.setState({
      curCityName: curCity.label,
    });
  }, []);