使用formik onsubmit中的react钩子值
我正在使用 Formik 创建一个表单。我按照此处的模式创建了表单: https://formik.org/docs/examples/basic
现在我想使用结果useParams 反应挂钩 (https://reach.tech/router/api/useParams)作为输入到 onSubmit 函数。
这是 Formik 文档中的 onSubmit 部分:
onSubmit={async (values) => {
await new Promise((r) => setTimeout(r, 500));
alert(JSON.stringify(values, null, 2));
}}
我尝试添加这一行:
onSubmit={async (values) => {
await new Promise((r) => setTimeout(r, 500));
const myValue = useParams()["myParam"]
alert(JSON.stringify(values, null, 2));
}}
其中 useParams
是从 'react-router-dom' 导入的
但这给了我一个错误: React Hook“useParams”无法在回调内调用。 React Hooks 必须在 React 函数组件或自定义 React Hook 函数中调用
我是 React/Formik 的新手,不知道如何从这里继续。如何获取 onSubmit 函数中 myParam
的值?
I am creating a form using Formik. I have created my form following the pattern here:
https://formik.org/docs/examples/basic
Now I want to use the result of the useParams react hook (https://reach.tech/router/api/useParams) as an input to the onSubmit function.
This is the onSubmit part from the Formik docs:
onSubmit={async (values) => {
await new Promise((r) => setTimeout(r, 500));
alert(JSON.stringify(values, null, 2));
}}
I tried adding this line:
onSubmit={async (values) => {
await new Promise((r) => setTimeout(r, 500));
const myValue = useParams()["myParam"]
alert(JSON.stringify(values, null, 2));
}}
where useParams
is imported from 'react-router-dom'
But this gives me an error:React Hook "useParams" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function
I am new to React/Formik and don't know how to proceed from here. How can I get the value of myParam
inside the onSubmit function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如前所述,您应该在组件级别而不是在回调(或非组件)中调用
useParams()
。中检查示例。
您可以在
As the error mentioned, you should call
useParams()
on the component level instead of in the callbacks (or non-components).You can check the example in this document again
According to your code, the correct way should be
React Hooks 是 React 用于执行 React 逻辑的特殊函数,您可以在 React 项目中找到它们,因为它们以 use 前缀命名:
useNameOfHook
React 钩子只能在 React 组件的主体内部调用,因此它们不能像您尝试的那样嵌套在另一个函数中。
(查看“钩子规则”以了解有关 React 中钩子的更多信息”) .
useParams
是一个 React Router 钩子,它返回路由参数,因此你只需在 React 组件中调用它,如下所示:React Hooks are particular functions that React uses to perform React logic, you can spot them in a React project since they are named with use prefix :
useNameOfHook
React hooks can be invoked only inside the body of a React component, so they can't be nested inside another function as you are trying to do.
(Check the "Rules of hooks" to find out more about hooks in React").
useParams
is a React Router hook which returns you route params, so you just need to call it inside your React component, like this: