我正在尝试实现一个非常简单的自定义钩子,称为useOpen,该钩子仅返回一个布尔值(isOpen)。我想基于isOpen状态在App.js中显示或隐藏一些文本。当前,什么都没有呈现,在App.js中尝试console.log(isOpen)给我未定义。预先感谢!
App.js
import React from 'react'
import useOpen from './CustomHooks/useOpen'
function App () {
const {isOpen} = useOpen;
return (
<div className='App'>
{isOpen && <p>isOpen</p>}
</div>
)
}
export default App
useOpen.js
import { useState } from 'react'
export default function useOpen() {
const [isOpen, setIsOpen] = useState(true)
return { isOpen }
}
答案 0 :(得分:0)
您缺少useOpen
上的括号。应该是useOpen()
。
const {isOpen} = useOpen; // missing ()
const {isOpen} = useOpen();
答案 1 :(得分:0)
尝试在组件上调用useOpen函数。
答案 2 :(得分:0)
您需要执行钩子才能获取其值 而且您无需将其放在对象中即可在另一侧解构
App.js
import React from 'react'
import useOpen from './CustomHooks/useOpen'
function App () {
//const {isOpen} = useOpen;
const isOpen = useOpen();
return (
<div className='App'>
{isOpen && <p>isOpen</p>}
</div>
)
}
export default App
useOpen.js
import { useState } from 'react'
export default function useOpen() {
const [isOpen, setIsOpen] = useState(true)
//return { isOpen }
return isOpen
}