gpt4 book ai didi

javascript - 如何在 React JS 中将 "dispatch"作为导出函数?

转载 作者:行者123 更新时间:2023-12-05 05:47:59 27 4
gpt4 key购买 nike

这是我的调度函数:

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() 函数。

Navbar.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;

但是我得到错误:

Error: Invalid hook call. Hooks can only be called inside of the bodyof a function component.

此处完整错误:

react-dom.development.js:14906 Uncaught 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 debugand fix this problem.at Object.throwInvalidHookError (react-dom.development.js:14906:1)at useContext (react.development.js:1504:1)at useReduxContext (useReduxContext.js:21:1)at useStore (useStore.js:20:1)at useDispatch (useDispatch.js:17:1)at DispatchRecipeID (DispatchRecipeID.js:6:1)at searchFunc (Navbar.js:71:1)at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)at invokeGuardedCallback (react-dom.development.js:4056:1)

enter image description here


如何解决这个错误?我想在“3 或 4 个 JS”文件中使用 DispatchRecipeID() 函数,例如 Navbar.js

请帮助我,谢谢:)

最佳答案

DispatchRecipeID.js

import { store } from 'redux/store'; 

代替

import { useDispatch } from "react-redux";

并调用 dispatch 作为 store 中的键

const DispatchRecipeID = (id) => { 
store.dispatch(UpdateRecipeID(id));
};

关于javascript - 如何在 React JS 中将 "dispatch"作为导出函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70899377/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com