![](/img/trans.png)
[英]Object literal may only specify known properties, and 'task' does not exist in type 'SetStateAction
[英]Object literal may only specify known properties, and ''app-id'' does not exist in type 'Headers'
下面是我从远程服务器获取数据的代码。
import * as React from 'react';
import { useEffect, useState } from 'react';
import Typography from '@mui/material/Typography';
import Container from '@mui/material/Container';
import TextField from '@mui/material/TextField';
import { styled } from '@mui/material/styles';
const URL = process.env.REACT_APP_URL;
const API = process.env.REACT_APP_API;
const APPID = process.env.REACT_APP_APPID;
const PageTitle = styled(Typography)({
fontSize: '30px',
marginBottom: '20px',
});
const SearchField = styled(TextField)({
width: '100%',
});
export default function Search() {
const [filterableData, setfilterableData] = useState();
useEffect(() => {
async function fetchData() {
const response = await fetch(`${URL}${API}`, {
method: 'GET',
headers: {
'app-id': APPID,
},
}); const data = await response.json();
console.log(data);
}
fetchData();
});
const search = (event) => {
console.log(event.target.value);
};
return (
<Container maxWidth="lg">
<PageTitle>Search</PageTitle>
<SearchField
id="outlined-search"
label="Enter search query"
type="search"
onChange={search}
/>
</Container>
);
}
它抛出以下错误。
Type '{ 'app-id': string | undefined; }' is not assignable to type 'HeadersInit | undefined'.
Type '{ 'app-id': string | undefined; }' is not assignable to type 'undefined'. TS2322
26 | const response = await fetch(`${URL}${API}`, {
27 | method: 'GET',
> 28 | headers: {
| ^
29 | 'app-id': APPID,
30 | },
31 | });
在互联网上搜索,我得到的解决方案与制作界面等有关。但这些解决方案都不适合我。 知道如何解决这个问题吗?
您应该尝试使用Headers
类
const headers = new Headers(); if(APPID) { headers.set('app-ip', APPID); } async function fetchData() { const response = await fetch(`${URL}${API}`, { method: 'GET', headers });
headers: {
'app-id': APPID as string,
},
以上解决了我的问题。
这似乎是lib.dom.d.ts
一个错误,但您仍然有一些选择来解决它。
fetch({
headers: {'app-id': APPID} as Headers
})
fetch({
// @ts-ignore
headers: {'app-id': APPID}
})
使用标题 Api。
fetch({ headers: new Headers({'app-id': APPID}) })
如果你想让旧浏览器兼容,你应该先导入一个Headers
polyfill。 请注意,下面的代码尚未经过测试。
(function(){
if(typeof Headers !== 'function') {
window.Headers = function(headers: Record<string, string>){return headers}
}
})()
对于上面列出的解决方案,我最推荐类型断言。
问题是 APPID 可以是未定义的,因为这是一个环境变量。 您应该测试 is not undefined 或强制使用!
如果您确定它已定义(即在调用函数之前进行测试)
const url = process.env.REACT_APP_URL;
const API = process.env.REACT_APP_API;
const APPID = process.env.REACT_APP_APPID;
async function fetchData():Promise<void> {
const response = await fetch(`${url}${API}`, {
method: 'GET',
headers: {
'app-id': APPID ?APPID:"", // or 'app_id':APPID!
},
}); const data = await response.json();
console.log(data);
}
fetchData();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.