![](/img/trans.png)
[英]Unhandled Rejection (TypeError): dispatch is not a function react js
[英]How to make "dispatch" as export function in React JS?
这是我的调度 function:
DispatchRecipeID.js
import { useDispatch } from "react-redux";
import { UpdateRecipeID } from "../store/action/recipeId";
const DispatchRecipeID = (id) => {
const dispatch = useDispatch(); // dispatch
dispatch(UpdateRecipeID(id));
};
export default DispatchRecipeID;
现在我在另一个React JS文件中使用这个DispatchRecipeID() function。
导航栏.js
import React, { useState } from "react";
import DispatchRecipeID from "../../middleware/DispatchRecipeID";
const Navbar = () => {
// inputbox value
const [input, setInput] = useState("");
// get search item info from inputID. using inputID.id
const [inputID, setInputID] = useState(null);
// search function
const dispatchRecipeID = ()=>{
if(input !== "" && input !== null ){
DispatchRecipeID(inputID.id)
}
return
}
// ....... some code
return(
<div>
<input type="text" value={input} onChange={(event,value)=>{ setInputID(value) }} />
<button onClick={dispatchRecipeID(input)} >Search</button>
</div>
)
}
export default Navbar;
但我得到错误:
错误:无效的挂钩调用。 钩子只能在 function 组件的主体内部调用。
这里的完整错误:
react-dom.development.js:14906 未捕获的错误:无效的钩子调用。 钩子只能在 function 组件的主体内部调用。 这可能由于以下原因之一而发生:
- 你可能有不匹配的 React 版本和渲染器(例如 React DOM)
- 您可能违反了 Hooks 规则
- 您可能在同一个应用程序中拥有多个 React 副本,请参阅https://reactjs.org/link/invalid-hook-call以获取有关如何调试和修复此问题的提示。 在 Object.throwInvalidHookError (react-dom.development.js:14906:1) 在 useContext (react.development.js:1504:1) 在 useReduxContext (useReduxContext.js:21:1) 在 useStore (useStore.js:20: 1) 在 HTMLUnknownElement.callCallback (react-dom.development.js:3945: 1) 在 Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1) 在 invokeGuardedCallback (react-dom.development.js:4056:1)
如何修复此错误? 我想在像 Navbar.js 这样的“3 或 4 个 JS”文件中使用DispatchRecipeID() function
请帮助我,谢谢:)
DispatchRecipeID.js
import { store } from 'redux/store';
代替
import { useDispatch } from "react-redux";
并调用 dispatch 作为 store 中的键
const DispatchRecipeID = (id) => {
store.dispatch(UpdateRecipeID(id));
};
只是为了提醒反应钩子中的重要规则之一,您不能在嵌套函数中使用钩子,如果您违反此规则,它们将不起作用
检查您的所有组件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.