简体   繁体   English

异步等待 typescript 反应

[英]async await typescript react

I am using async and await for getting response from an api but when I using it with react type script it keeps我正在使用异步并等待从 api 获得响应,但是当我将它与反应类型脚本一起使用时,它会保持

TS2339: Property 'email' does not exist on type 'AxiosResponse<any, any>'. TS2339:“AxiosResponse<any,any>”类型上不存在属性“email”。

I am following a course but it seems he work in older version is there any way to achieve that我正在学习一门课程,但似乎他在旧版本中工作有什么办法可以实现

here is my function for submit form这是我的 function 用于提交表格

const submitRegister = async (e: SyntheticEvent)=>{
    e.preventDefault();
    const { email:email } = await axios.post('http://lovalhost/8000');
}

any help will be appreciated任何帮助将不胜感激

'http://lovalhost/8000' 'http://lovalhost/8000'

Do you mean 'localhost:8000'?你的意思是“本地主机:8000”吗?

const { email:email } = await axios.post()常量 { email:email } = 等待 axios.post()

Here you are destructing the response for the email property.在这里,您正在破坏email属性的响应。 If you look at the actual response you will find that you are probably looking for response.data.email如果您查看实际响应,您会发现您可能正在寻找response.data.email

Try using.then and.catch as well.尝试使用.then 和.catch。

const email = await axios.post('http://lovalhost/8000').then(({data}) => data.email).catch(error => console.error(error))

The response from await axiosPost(...) will be an object containing a data key that holds the data returned from the request. await axiosPost(...)的响应将是一个 object ,其中包含一个保存从请求返回的数据的data键。

const response = await axios.post('http://lovalhost/8000');
console.log(response.data.email) // this is where your email value will be (in case the request is succesful)

You can also let typescript know what your response data will look like, by adding the type to the call.您还可以通过将类型添加到调用中,让 typescript 知道您的响应数据将是什么样子。

const response = await axios.post<{email: string}>('http://lovalhost/8000');

You need to access the data object within the response as can be seen here https://axios-http.com/docs/res_schema您需要访问响应中的data object,如下所示https://axios-http.com/docs/res_schema

Try something like this:尝试这样的事情:

const { data } = await axios.post('http://lovalhost/8000');
const { email } = data

or maybe store the response object because that will also have information about the response status etc.或者可能存储response object 因为这也将包含有关响应状态等的信息。

try {
    const response = await axios.post('http://lovalhost/8000');

    if (response.status != 200) {
       // throw
    }

    const { email } = response.data
    return email
}
catch (ex) {
    console.error(ex)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM