![](/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.