Sha*_*aze 3 google-maps typescript reactjs react-redux
我收到此错误:
D:/Downloads/Uber-Website-Clone-master/src/App.tsx D:/Downloads/Uber-Website-Clone-master/src/App.tsx(17,7) 中的 TypeScript 错误:没有重载与此调用匹配。重载第 1 个(共 2 个)“(props: Readonly): LoadScript”,出现以下错误。
D:/Downloads/Uber-Website-Clone-master/src/App.tsx
TypeScript error in D:/Downloads/Uber-Website-Clone-master/src/App.tsx(17,7):
No overload matches this call.
Overload 1 of 2, '(props: Readonly<LoadScriptProps>): LoadScript', gave the following error.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
Overload 2 of 2, '(props: LoadScriptProps, context?: any): LoadScript', gave the following error.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'. TS2769
15 | <div className="App">
16 | <LoadScript
> 17 | googleMapsApiKey={process.env.REACT_APP_GOOGLE_TOKEN}
| ^
18 | libraries={['places']}
19 | >
20 | <CoordinatesProvider>
Run Code Online (Sandbox Code Playgroud)
这是代码:
import React, { useEffect } from 'react';
import { LoadScript } from '@react-google-maps/api';
import './global.css';
import CoordinatesProvider from './context/coordinates';
import Header from './components/Header';
import Map from './components/Map';
import Search from './components/Search';
function App() {
return (
<div className="App">
<LoadScript
googleMapsApiKey={process.env.REACT_APP_GOOGLE_TOKEN}
libraries={['places']}
>
<CoordinatesProvider>
<Header />
<Search />
<Map />
</CoordinatesProvider>
</LoadScript>
</div>
);
}
export default App;Run Code Online (Sandbox Code Playgroud)
process.env.REACT_APP_GOOGLE_TOKEN如果在环境中设置了该值,则返回一个字符串undefined;如果未设置,则返回一个字符串。有了这些信息,我们来看看错误:
> 17 | googleMapsApiKey={process.env.REACT_APP_GOOGLE_TOKEN}
Run Code Online (Sandbox Code Playgroud)
您正在尝试将其设置googleMapsApiKey为组件的支柱LoadScript。LoadScript肯定需要字符串类型才能运行,并且它不接受任何其他类型。而我们的process.env可能会返回一个未定义的值。
要解决这个问题,您需要确保process.env.REACT_APP_GOOGLE_TOKEN是一个字符串。您可以通过多种方式完成此操作:事先检查变量并通过抛出错误或显示错误消息或设置默认值来采取适当的操作。这是我的首选方式:
function App() {
const key = process.env.REACT_APP_GOOGLE_TOKEN;
if(!key){
// you can throw error here and
// let [Error Boundary](https://reactjs.org/docs/error-boundaries.html)
// handle it
// or return an component that says "Google Token is not set"
throw new Error('Google token is not set');
}
return (
<div className="App">
<LoadScript
googleMapsApiKey={key}
libraries={['places']}
>
<CoordinatesProvider>
<Header />
<Search />
<Map />
</CoordinatesProvider>
</LoadScript>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4605 次 |
| 最近记录: |