Reactjs REACT-Typescript获取/axios错误-从类型';地址[]和#x27;:长度,弹出,推,concat和28更多。TS2740 从“/Address.model”导入{Address}; export const get=async():Promise=>{ 返回等待获取(`${APIRL}`) 。然后(响应=>{ 如果(!response.ok){ 抛出新错误(response.statusText) } 返回response.json()作为承诺; }) //--------------来自 React.useffect(()=>{ 让newArr:Address[]=get(); SET实体(newArr); } , [])
//-------------抛出以下错误:Reactjs REACT-Typescript获取/axios错误-从类型';地址[]和#x27;:长度,弹出,推,concat和28更多。TS2740 从“/Address.model”导入{Address}; export const get=async():Promise=>{ 返回等待获取(`${APIRL}`) 。然后(响应=>{ 如果(!response.ok){ 抛出新错误(response.statusText) } 返回response.json()作为承诺; }) //--------------来自 React.useffect(()=>{ 让newArr:Address[]=get(); SET实体(newArr); } , []),reactjs,typescript,axios,fetch,Reactjs,Typescript,Axios,Fetch,//-------------抛出以下错误: 类型“Promise”缺少类型“Address[]”中的以下属性:长度、pop、push、concat和28个以上。TS2740忽略有问题的强制转换(参见as Promise),您需要等待get()函数获取地址[]类型,因此 import {Address} from './address.model'; export const get = async ():Promise<Address[]> => { r
类型“Promise”缺少类型“Address[]”中的以下属性:长度、pop、push、concat和28个以上。TS2740忽略有问题的强制转换(参见
as Promise
),您需要等待get()
函数获取地址[]
类型,因此
import {Address} from './address.model';
export const get = async ():Promise<Address[]> => {
return await fetch(`${apiUrl}`)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json() as Promise<Address[]>;
})
//--------------caling from
React.useEffect(() => {
let newArr: Address[] = get() ;
setEntities(newArr);
} , [])
很好。但是添加异步会引发以下错误:“()=>Promise”类型的参数不可分配给“EffectCallback”类型的参数。类型“Promise”不可分配给类型“void |”(()=>void | undefined)”。类型“Promise”不可分配给类型“()=>void | undefined.键入'Promise'与签名'():void | undefined'不匹配。TS2345async inside useEffect需要这样:。我将继续更改答案。啊,是的,我总是犯这个错误。我将更新我的代码块以匹配下一个人。
React.useEffect(() => {
async get() => {
// do the IO
}
const newArr: Address[] = await get()
setEntities(newArr)
} , [])