我最近开始在我的 React 应用程序中构建自定义钩子(Hook),并且一直在关注 React 网站上的文档。但是,我正在构建的钩子(Hook)不需要返回值,因为它们在初始化时为 Redux 设置数据。
例子:
// custom hook
export const useSetup() {
useEffect(() => {
if (data) fetch().then(data => dispatch(setInit(data)))
}, [dispatch])
}
// functional component
export function Details() {
useSetup()
我找不到明确说明钩子(Hook)需要返回任何东西的文档。但是,我找不到钩子(Hook)不返回某些内容的示例。有人可以建议这种方法是否正确吗?
最佳答案
是的,你的方法是正确的。 React 钩子(Hook)不需要返回任何东西。 React documentation指出:
We don’t have to return a named function from the effect. We called it cleanup here to clarify its purpose, but you could return an arrow function or call it something different.
作为参数传递给钩子(Hook)的函数的返回值在它所属的 React 组件的生命周期中具有特殊用途。本质上,该返回值应该是一个函数,并在带有钩子(Hook)的组件重新渲染或卸载之前执行。 React 文档将这种钩子(Hook)称为“清理效果”。
React 文档使用下面的示例来显示
useEffect
钩子(Hook)看起来像:const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
如您所见,用作 useEffect
参数的匿名函数没有 return
陈述。您可以通过稍微更改函数以记录返回值来验证这一点:
const count = 0;
const a = () => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
}
console.log(a());
这将打印 undefined
.您也可以使用
console.log
在 useEffect
函数来查看它是否也返回 undefined
.如果您将 Hook 更改为:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
return () => {
console.log('cleanup');
}
});
你会看到 "cleanup"
每次组件重新渲染或卸载时的消息。您必须通过某种方式更新组件的状态来触发重新渲染。
关于javascript - React 钩子(Hook)需要返回一个值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62148155/