关键词:
【中文标题】React 和 Typescript,Axios 响应的类型都有哪些?【英文标题】:React and Typescript, which types for Axios response?React 和 Typescript,Axios 响应的类型有哪些? 【发布时间】:2020-09-24 19:06:22 【问题描述】:我正在尝试从返回以下内容的 API 中呈现一个简单的用户列表:
["UserID":2,"FirstName":"User2","UserID":1,"FirstName":"User1"]
我不完全了解如何处理带有类型的 Axios 响应。打字稿错误是
Type ' | id: number; firstName: string; ' is not assignable to type 'IntrinsicAttributes & UserListProps & children?: ReactNode; '.
Property 'items' is missing in type '' but required in type 'UserListProps'.
来自下面Users.tsx
文件中的<UserList />
元素。我的User
接口错了吗?
import React, useEffect, useState, Fragment from 'react';
import UserList from './UserList';
import axios, AxiosResponse from 'axios';
interface User
id: number;
firstName: string;
const Users: React.FC = (props) =>
const [users, setUserList] = useState<User>();
useEffect(() =>
// Use [] as second argument in useEffect for not rendering each time
axios.get('http://localhost:8080/admin/users')
.then((response: AxiosResponse) =>
console.log(response.data);
setUserList( response.data );
);
, []);
return (
<Fragment>
<UserList ...users />
</Fragment>
);
;
export default Users;
下面是我的UserList.tsx
。
import React, Fragment from 'react';
interface UserListProps
items: id: number, firstName: string[];
;
const UserList: React.FC<UserListProps> = (props) =>
return (
<Fragment>
<ul>
props.items.map(user => (
<li key=user.id>
<span>user.firstName</span>
/* not call delete function, just point to it
// set this to null in bind() */
</li>
))
</ul>
</Fragment>
);
;
export default UserList;
【问题讨论】:
【参考方案1】:有generic get
method defined in axios/index.d.ts
get<T = never, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig<T>): Promise<R>;
例子
interface User
id: number;
firstName: string;
axios.get<User[]>('http://localhost:8080/admin/users')
.then(response =>
console.log(response.data);
setUserList( response.data );
);
--编辑
我认为您将列表以错误的方式传递给子组件。
const [users, setUserList] = useState<User[]>([]);
<UserList items=users />
interface UserListProps
items: User[];
;
const UserList: React.FC<UserListProps> = (items) =>
return (
<Fragment>
<ul>
items.map(user => (
<li key=user.id>
<span>user.firstName</span>
</li>
))
</ul>
</Fragment>
);
;
【讨论】:
谢谢,所以我应该使用axios.get<User>
而不是useState<User>()
?如果我尝试这样做,Typescript 会抱怨 useState()
未定义。
更新了答案。起初我以为你只是得到一个对象,但这实际上是一个数组。只需将[]
括号放在几个地方
我认为现在唯一缺少的部分是我如何初始化useState()
。我明白了:Argument of type 'User[]' is not assignable to parameter of type 'SetStateAction<undefined>'. Type 'User[]' provides no match for the signature '(prevState: undefined): undefined'.ts(2345)
你必须用空数组初始化useState([])
。否则,您必须扩展类型 useState<User[] | undefined>()
添加检查变量是否在子组件中未定义并对其进行处理【参考方案2】:
如果您不希望 axios 推断值 response
的类型,则需要在调用 axios.get
时提供类型参数。
当您useState
创建用户数组时,您传递的类型参数不正确。
正确的方法
interface User
id: number;
firstName: string;
// initialized as an empty array
const [users, setUserList] = useState<User[]>([]); // users will be an array of users
例如,
import React, useEffect, useState, Fragment from 'react';
import UserList from './UserList';
import axios from 'axios';
interface User
id: number;
firstName: string;
// you can export the type TUserList to use as -
// props type in your `UserList` component
export type TUserList = User[]
const Users: React.FC = (props) =>
// you can also use User[] as type argument
const [users, setUserList] = useState<TUserList>();
useEffect(() =>
// Use [] as second argument in useEffect for not rendering each time
axios.get<TUserList>('http://localhost:8080/admin/users')
.then((response) =>
console.log(response.data);
setUserList( response.data );
);
, []);
return (
<Fragment>
<UserList ...users />
</Fragment>
);
;
export default Users;
如果您选择导出类型type TUserList = User[]
,您可以在UserList
组件中使用它作为道具类型。例如,
import React, Fragment from 'react';
import TUserList from './Users';
interface UserListProps
items: TUserList // don't have to redeclare the object again
;
const UserList: React.FC<UserListProps> = (props) =>
return (
<Fragment>
<ul>
props.items.map(user => (
<li key=user.id>
<span>user.firstName</span>
/* not call delete function, just point to it
// set this to null in bind() */
</li>
))
</ul>
</Fragment>
);
;
export default UserList;
【讨论】:
关于导出TUserList
类型非常好,非常感谢您的出色回答:)
我很高兴它有帮助。React-query 和 Typescript - 如何正确输入突变结果?
】React-query和Typescript-如何正确输入突变结果?【英文标题】:React-queryandTypescript-howtoproperlytypeamutationresult?【发布时间】:2021-11-0513:50:31【问题描述】:我有一个简单的钩子,将axios调用包装在ReactQuery中:functionuseInviteTeamMember(onS... 查看详情
使用 Typescript 创建 React 组件
】使用Typescript创建React组件【英文标题】:CreatingaReactcomponentwithTypescript【发布时间】:2021-08-3006:07:21【问题描述】:我最近在学习typescript,我必须使用良好的实践将一个假的react组件转换为typescript。目前我有类似的东西importaxio... 查看详情
Axios、Typescript 和 Promise
】Axios、Typescript和Promise【英文标题】:Axios,Typescript,andPromises【发布时间】:2018-02-2518:59:10【问题描述】:这可能更像是一个TypeScript问题。我有一个REST方法,它通过Vue操作在我的http库中调用。我希望resolve()方法返回类型化数组... 查看详情
如何使用 Axios 和 Typescript 等待响应?
】如何使用Axios和Typescript等待响应?【英文标题】:HowcanIwaitforaresponseusingAxiosandTypescript?【发布时间】:2019-12-0909:55:35【问题描述】:我需要您的帮助来调整我的方法以等待axios响应。基本上,我向WebService发送请求,我需要等待... 查看详情
VueJs Axios 和 Typescript
】VueJsAxios和Typescript【英文标题】:VueJsAxiosandTypescript【发布时间】:2018-04-2920:48:38【问题描述】:我得到了一个开发项目的基地。用Vue和Typescript制作的,网上支持的不多。我目前需要进行几次API调用以检查服务的可用性,并且... 查看详情
Axios 和 Typescript 给出一个类型的 promise 拒绝错误
】Axios和Typescript给出一个类型的promise拒绝错误【英文标题】:Axios&Typescriptgiveerrorfrompromiserejectionatype【发布时间】:2021-12-1012:59:56【问题描述】:我目前面临的问题是我不能使用从承诺拒绝返回的错误,因为它不能用Typescript... 查看详情
如何在 Vue 和 TypeScript 应用中正确的全局注册 axios
】如何在Vue和TypeScript应用中正确的全局注册axios【英文标题】:HowtoProperlyRegisteraxiosGloballyinVue&TypeScriptApplication【发布时间】:2019-11-1223:54:10【问题描述】:我一直在与Vue、TypeScript和Axios进行斗争,但我无法找到令人满意的解... 查看详情
使用 axios、TypeScript 模板和异步函数对 VueJS 进行单元测试
】使用axios、TypeScript模板和异步函数对VueJS进行单元测试【英文标题】:UnittestingVueJSwithaxios,TypeScripttemplate,andasyncfunctions【发布时间】:2019-04-1721:41:59【问题描述】:我正在尝试对在其mounted()挂钩中进行HTTP调用的组件进行单元测... 查看详情
带有 Axios 和 TypeScript 的 VueJS3 - 找不到变量
】带有Axios和TypeScript的VueJS3-找不到变量【英文标题】:VueJS3withAxiosandTypeScript-Cannotfindvariables【发布时间】:2021-09-1615:49:05【问题描述】:我无法使用axios+vuejs3+ts访问方法内的this.somethingHere变量。模板代码(非必须):<template&g... 查看详情
如何使用 vuex 和 typescript 将 axios 调用移动到自己的方法中
】如何使用vuex和typescript将axios调用移动到自己的方法中【英文标题】:Howtomoveanaxioscallintoitsownmethodusingvuexandtypescript【发布时间】:2022-01-0617:50:29【问题描述】:我在vuex操作中有一个方法,它调用api并更新用户信息。我正在尝试... 查看详情
如何测试使用自定义 TypeScript React Hook 的组件?
】如何测试使用自定义TypeScriptReactHook的组件?【英文标题】:HowtotestacomponentwhichisusingacustomTypeScriptReactHook?【发布时间】:2020-01-1511:58:42【问题描述】:我目前正在Typescript中编写一个React组件,它使用一个名为useAxios的axios-hooks钩... 查看详情
绝对导入:React 和 Typescript
】绝对导入:React和Typescript【英文标题】:AbsoluteImports:ReactandTypescript【发布时间】:2020-07-2809:16:29【问题描述】:背景我有一个使用create-react-app和typescript引导的React应用程序。随着应用程序的增长,(目标)我想实现绝对导入... 查看详情
react/axios Auth 和 CORS 问题
】react/axiosAuth和CORS问题【英文标题】:react/axiosAuthandCORSissue【发布时间】:2020-02-1204:02:42【问题描述】:使用:返回:Laravel/Passport前面:ReactJs/Axios我想在我的页面中获取数据,如果我运行:axios.get(\'http://localhost:8000/api/posts\').t... 查看详情
来自配置的 React 和 Typescript 动态组件
】来自配置的React和Typescript动态组件【英文标题】:ReactandTypescriptdynamiccomponentfromconfig【发布时间】:2021-08-1305:28:50【问题描述】:我正在尝试使用reactjs和typescript构建一个动态菜单系统。我的配置如下所示:importTableIconfrom"@heroi... 查看详情
如何使用 React 和 TypeScript 设置 Electron?
】如何使用React和TypeScript设置Electron?【英文标题】:HowtosetupElectronwithReactandTypeScript?【发布时间】:2018-04-2905:33:42【问题描述】:我正在使用Electron编写应用程序,使用Babel编写React(jsx)。今天晚上我改用TypeScript,但我不知道如... 查看详情
CORS 与 React、Webpack 和 Axios
】CORS与React、Webpack和Axios【英文标题】:CORSwithReact,WebpackandAxios【发布时间】:2018-04-0406:45:48【问题描述】:如何使用webpack和axios在react前端应用中设置CORSHeader。我想从API网址获得响应。我是否必须使用express设置单独的服务器,... 查看详情
使用 React 和 Axios 从 Express API 下载文件
】使用React和Axios从ExpressAPI下载文件【英文标题】:DownloadfilefromExpressAPIusingReactandAxios【发布时间】:2020-02-2601:50:40【问题描述】:在使用带有ExpressAPI的React客户端时,React客户端如何下载由ExpressAPI发送的文件?问题:如果我在... 查看详情
React HOC 和 TypeScript 3.2
】ReactHOC和TypeScript3.2【英文标题】:ReactHOCandTypeScript3.2【发布时间】:2019-05-0212:40:24【问题描述】:随着TypeScript在v3.2中改进其JSX类型检查,我们现在无法正确键入我们的HOC。有人可以为TypeScript3.2修复以下HOC中的类型吗?importCom... 查看详情