react,V6,引入withFormik后报错的问题

在使用的react版本如下:

img


已写的部分代码:

function Login() {
// ...
}
Login = withFormik({
const navigate = useNavigate()
const { state } = useLocation()
if (!state) {
 // 如果进入到该页面,直接调用go(-1)
// props.history.go(-1)
navigate(-1)
} else {
// props.history.replace(props.location.state.from.pathname)
navigate(state.from.pathname,{replace: true})
      }
})(Login)
export default Login

chrome浏览器报错:

img


**Uncaught (in promise) 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:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

中文翻译:
未捕获(在promise中)错误:钩子调用无效。钩子只能在函数组件的主体内部调用。这可能是由于以下原因之一:
1.React和渲染器的版本可能不匹配(例如React DOM)
2.你可能违反了勾手规则
3.同一应用程序中可能有多个React副本
看见https://reactjs.org/link/invalid-hook-call获取有关如何调试和修复此问题的提示。**

经过检查,排除了reat dom版本不够高的问题,估计原因是const navigate = useNavigate()和const { state } = useLocation()这两句代码写的位置有问题导致违反了hook规则

于是尝试把这两句代码写在其他位置,例如这里,navigate和state变成暗色:

img


同时,chrome浏览器报错说navigate和state未定义

请问代码出了什么问题?正确的代码是什么?请展示代码举例说明。

const navigate = useNavigate()
好像这个只能放在主函数的下面,比如你那个Login函数下面