【发布时间】:2022-01-05 14:04:34
【问题描述】:
我想调用一个自定义钩子,它会在单击按钮时发送电子邮件。
customHook.ts
async function sendEmail(userName: string, userEmail: string, userPhone: string) {
const mailToUser = {
to: userEmail,
subject: mail.subject,
body: mail.body,
};
await fetch(`/api/sendEmail`, {
method: `POST`,
headers: { 'Content-Type': `application/json` },
body: JSON.stringify(mailToUser),
});
console.log(mailToUser);
}
export default sendEmail;
这是点击按钮时需要调用发送邮件的自定义钩子文件
contact.tsx
import sendEmail from 'src'
export const Contact = (props:any) {
const userName = `Name`;
const userEmail = `email`;
const userPhone = `333333333`;
return (
<button onClick={() => sendEmail(userName, userEmail, userPhone)}>Contact</button>
)
}
点击按钮时出现的错误是:
**Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:**
【问题讨论】:
-
sendEmail甚至不是一个钩子,因为您没有使用任何状态或效果。在 body 组件之外,你有useState或useEffect吗? -
您的代码可以正常工作(修复一些语法问题):codesandbox.io/s/vibrant-black-i2j87?file=/src/App.js
标签: reactjs react-hooks next.js typescript-typings