项目目录如下:
在此index.html中加入如下代码即可:
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><link rel="icon" href="%PUBLIC_URL%/favicon.ico" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="theme-color" content="#000000" /><metaname="description"content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /><!--manifest.json provides metadata used when your web app is installed on auser's mobile device or desktop. See /web/fundamentals/web-app-manifest/--><link rel="manifest" href="%PUBLIC_URL%/manifest.json" /><!--Notice the use of %PUBLIC_URL% in the tags above.It will be replaced with the URL of the `public` folder during the build.Only files inside the `public` folder can be referenced from the HTML.Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" willwork correctly both with client-side routing and a non-root public URL.Learn how to configure a non-root public URL by running `npm run build`.--><!-- 引入百度地图api的js文件 --><script type="text/javascript" src="https://api./api?v=2.0&ak=3RCAu7SsZ0ThFxGGbPaHv8YGM3TAEnGZ"></script><title>好客租房</title></head><body><!-- 百度地图的AK:3RCAu7SsZ0ThFxGGbPaHv8YGM3TAEnGZ --><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><!--This HTML file is a template.If you open it directly in the browser, you will see an empty page.You can add webfonts, meta tags, or analytics to this file.The build step will place the bundled scripts into the <body> tag.To begin the development, run `npm start` or `yarn start`.To create a production bundle, use `npm run build` or `yarn build`.--></body></html>
需要注意的是: react项目中,全局变量挂载在window下
new window.BMap.LocalCity();
import axios from "axios";/*** 获取当前所在城市名称* @returns {string} 当前所在城市*/export const getCurrentCity = () => {const localCity = JSON.parse(localStorage.getItem("hkzf_city"));if (!localCity) {return new Promise((resolve, reject) => {const myCity = new window.BMap.LocalCity();myCity.get(async (res) => {try {const {data: reslust } = await axios.get("http://localhost:8080/area/info",{params: {name: res.name,},});console.log(reslust)localStorage.setItem("hkzf_city", JSON.stringify(reslust.body));resolve(reslust.body);} catch (e) {reject(e);}});});} else {// 没有的时候返回的是一个promise,为了保持统一,//没有值的时候也要返回一个promise对象// 此处promise不会失败,所以,此处只要返回一个成功的promise即可return Promise.resolve(localCity)}};