我有一個 React 應用程式的問題。我需要在我的全域狀態中保留一系列專案。
這是我的鉤子:
import { useContext } from "react";
import GlobalContext from "../context/GlobalProvider";
const useGlobal = () => {
return useContext(GlobalContext);
}
export default useGlobal;
這是我的提供者:
import { createContext, useState } from "react";
const GlobalContext = createContext({});
export const GlobalProvider = ({ children }) => {
const [global, setGlobal] = useState({});
return (
<GlobalContext.Provider value={{ global, setGlobal }}>
{children}
</GlobalContext.Provider>
)
}
export default GlobalContext;
在我的 App.js 中,我有:
import useGlobal from "../hooks/useGlobal.js";
const { setGlobal } = useGlobal();
const handleGotoA = () => {
const id_G = item
const id_G1 = item1
const id_G2 = item2
setGlobal({ id_G, id_G1, id_G2 });
}
我收到此錯誤:
"setGlobal is not a function"
而且我找不到也無法理解原因,任何幫助將不勝感激。
uj5u.com熱心網友回復:
確保您在函式const { setGlobal } = useGlobal()內部App而不是外部呼叫此行,因為它是一個鉤子,它應該遵循鉤子規則。就像是:
const App = ()={
//...
const { setGlobal } = useGlobal(); // inside and at the top level of the component
//...
}
此外,global是 JavaScript 中的保留名稱。為避免混淆和可能的錯誤,請使用其他名稱,例如globalData. 最后確保App被包裹在里面GlobalProvider,像這樣:
<GlobalProvider >
<App/>
</GlobalProvider>
uj5u.com熱心網友回復:
useContext/useGlobal是鉤子,所以你不能在React component.
另外,請確保您的hadleGoToA組件位于GlobalContextProvider:
import useGlobal from "../hooks/useGlobal.js";
const HandleGotoA = () => { //Changed to uppercase to follow convention
const { setGlobal } = useGlobal();
const id_G = item
const id_G1 = item1
const id_G2 = item2
setGlobal({ id_G, id_G1, id_G2 });
}
uj5u.com熱心網友回復:
我認為這與這條線有關
const { setGlobal } = useGlobal();
我認為應該是:
const { setGlobal } = useGlobal;
因為使用括號,您正在呼叫函式,因此 setGlobal 是 useGlobal 函式的結果,而不是函式本身。
uj5u.com熱心網友回復:
首先,您不能在組件外部使用鉤子或自定義鉤子。https://reactjs.org/docs/hooks-rules.html
//custom hook
const useHandleGoToA = () => {
// this line moved inside the hook
const { setGlobal } = useGlobal();
const id_G = item
const id_G1 = item1
const id_G2 = item2
setGlobal({ id_G, id_G1, id_G2 });
}
// component
const ComponentA = () => {
// this line moved inside the component.
const { setGlobal } = useGlobal();
const id_G = item
const id_G1 = item1
const id_G2 = item2
setGlobal({ id_G, id_G1, id_G2 });
return null;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/494005.html
標籤:javascript 反应
