是的,你的做法是正确的。 React hooks 不需要返回任何东西。这反应文档 https://reactjs.org/docs/hooks-effect.html指出:
我们不必从效果中返回命名函数。我们称之为
在这里进行清理以阐明其目的,但您可以返回一个箭头
函数或称其为不同的东西。
作为参数传递给钩子的函数的返回值在其所属的 React 组件的生命周期中具有特殊用途。本质上,该返回值应该是一个函数,并在带有钩子的组件重新渲染或卸载之前执行。 React 文档将这种钩子称为“清理效果”。
React 文档使用下面的示例来展示什么是useEffect
钩子看起来像:
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
on the useEffect
函数可以看到它也返回undefined
.
如果您将挂钩更改为:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
return () => {
console.log('cleanup');
}
});
你会看到"cleanup"
每次组件重新渲染或卸载时都会显示消息。您必须通过以某种方式更新组件的状态来触发重新渲染。