可能的解决方案
如果唯一的问题是让getCertificate
人被执行,那么你可以try 这样做:
import React, { useState } from "react";
const serverUri = "http://myserver.com";
export default function Certificate() {
const [id, setId] = useState("");
async function getCertificate(id: string): Promise<Response> {
console.log("in getCertificate");
const resp = await fetch(`${serverUri}/certs/${id}`);
console.log(`Response data: ${await resp.json()}`);
return resp;
}
return (
<form onSubmit={async (event: any) => {
event.preventDefault();
try {
const response = await getCertificate(id);
const data = await response.json();
console.log(data);
} catch (err) {
console.error(err);
}
console.log("getCertificate completed");
}}>
<label>
Certificate ID:
<input type="text" value={id} onChange={e => setId(e.target.value)} />
</label>
<button type="submit">Submit</button>
</form>
);
}
正如你在屏幕截图上看到的,in getCertificate
被打印到控制台.
它之所以不能执行
让我们仔细看看原始函数:
() => {
async() => await getCertificate(id)
.then(async resp => await resp.json())
.then(data => console.log(data))
.catch(err => console.error(err))
console.log("getCertificate completed")
}
正如您在这里看到的,您在这里只定义了一个匿名的异步箭头函数(没有将该函数赋给任何变量,因此该函数永远不会被调用),然后执行console.log
.所以console.log
是唯一真正被执行的东西.
此外,在呼叫getCertificate
之前添加await
,这不是必需的,可能会导致额外的混淆.
让我们简化一下这行代码
async() => await getCertificate(id)
.then(async resp => await resp.json())
.then(data => console.log(data))
.catch(err => console.error(err))
因此,首先我们将重新格式化代码以查看其 struct :
async() => {
await getCertificate(id)
.then(async resp => await resp.json())
.then(data => console.log(data))
.catch(err => console.error(err))
}
然后,我们删除不必要的函数定义:
await getCertificate(id)
.then(async resp => await resp.json())
.then(data => console.log(data))
.catch(err => console.error(err))
然后我们将删除不必要的await
:
getCertificate(id)
.then(async resp => await resp.json())
.then(data => console.log(data))
.catch(err => console.error(err))
另一种解决方案
因此,使用上一节中的变换,我们可以得到另一种定义整个函数的方法.
(event: any) => {
event.preventDefault();
getCertificate(id)
.then(async resp => await resp.json())
.then(data => console.log(data))
.then(() => console.log("getCertificate completed with no errors"))
.catch(err => console.error(err))
.then(() => console.log("getCertificate completed with errors"))
}
附注:
请注意,两种解决方案中的event.preventDefault()
都将阻止表单数据的实际传输,并强制处理JS中的所有内容.它是可选的,可以省略.