![](/img/trans.png)
[英]React complains that hook is not used inside of a body function when my component is passed into another component to render
[英]React custom hook setValue is undefined when used inside another component
我有一个useLocalStorage
挂钩。 如果我直接在我的组件中使用它,当我尝试更新值时,我得到一个错误setValue
is not a function。它实际上是未定义的。
这是代码片段
// https://github.com/Ibaslogic/localstorage-react-hook-project/blob/main/src/useLocalStorage.js
import { useState, useEffect } from "react";
function getStorageValue(key, defaultValue) {
// getting stored value
if (typeof window !== "undefined") {
const saved = localStorage.getItem(key)
const initial = saved !== null ? JSON.parse(saved) : defaultValue
return initial;
}
}
export const useLocalStorage = (key, defaultValue) => {
const [value, setValue] = useState(() => {
return getStorageValue(key, defaultValue)
})
useEffect(() => {
// storing input name
localStorage.setItem(key, JSON.stringify(value))
}, [key, value])
return [value, setValue]
}
export default useLocalStorage
这是我想在其中使用此挂钩的组件:
import useLocalStorage from '../hooks/useLocalStorage'
const MyComponent = () => {
const [val, setVal] = useLocalStorage('test', '')
..
useEffect(() => {
setVal('thats a test')
..
})
该组件还有一个 Context(通过 useContext)。 如果我在上下文中使用 useLocalStorage 挂钩,并将其导入 MyComponent - 代码有效:
// context/MyProvider.js
import { createContext } from "react";
import useLocalStorage from '../hooks/useLocalStorage'
const MyContext = createContext({})
export const MyProvider = ({ children }) => {
const [value, setValue] = useLocalStorage("test", null)
..
return (
<MyContext.Provider value={{ value, setValue }}>
{children}
</MyContext.Provider>
)
}
export default AuthContext
// components/MyComponent.js
import { useContext } from "react";
import MyContext from "../context/MyProvider";
const MyComponent = () => {
const { value, setValue } = useContext(MyContext)
..
useEffect(() => {
setValue('thats a test')
..
})
有人可以解释一下吗? 为什么我不能对我的组件使用自定义挂钩?
我做了一个codesandbox ,问题是保存未定义。 您可以将 useLocalStorage 挂钩更改为此,它对我有用:
function getStorageValue(key, defaultValue) {
// getting stored value
if (typeof window !== "undefined") {
const saved = localStorage.getItem(key);
const initial =
saved !== null && saved !== "undefined"
? JSON.parse(saved)
: defaultValue;
return initial;
}
}
您需要将<MyComponent/>
放在<MyProvider><MyComponent/></MyProvider>
中才能调用使用它的上下文
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.