gpt4 book ai didi

reactjs - 需要更清楚的解释如何避免使用 React hooks 无限重新渲染

转载 作者:行者123 更新时间:2023-12-05 02:55:06 25 4
gpt4 key购买 nike

对 React hooks 不是很熟练,之前用过很多类组件,希望你能原谅。

当前代码导致无限重新渲染,我想我理解为什么 - 整个函数体在重新渲染时被调用。

const NavTabs = () => {
const classes = useStyles();

const [categories, setCategories] = React.useState();
const axiosPromise = getRequest(consts.categoriesURL);

axiosPromise.then(data => {
setCategories(data.value);
})

return (
<div className={classes.root}>
<AppBar position="static">
</AppBar>
{categories && <DynamicTabs categories={categories}/>}
</div>
);
}

我想我可以做类似 if (!categories) { const axiosPromise [...] 之类的事情,即仅在尚未填充类别时才执行 http 请求。我想这也可以通过 useEffect 来解决?或者将钩子(Hook)包装在内部函数中?

我想我真正的问题是——为什么 React 会重新渲染整个函数体?它不应该只重新渲染返回函数吗?那么使用将在每次渲染时重新运行的 Hook 有什么意义呢?

相对于类组件——函数体中的代码不应该相当于类组件中的构造函数代码,而返回函数——相当于render方法吗?

最佳答案

I guess I could do something like if (!categories) { const axiosPromise [...] and so forth, i.e. do the http request only if categories haven't been populated yet. I guess this could also be solved by useEffect? Or wrapping the hook in an internal function?

是的,useEffect 是去这里的方法。发出请求并将结果设置为状态是副作用,在您的情况下应该只运行一次。我们可以使用 useEffect 轻松实现。

I guess my real question is - why is React re-rendering the entire function body? Shouldn't it re-render only the return function? And then what is the point of using hooks that will be re-run on every render?

React 没有办法拆分一个 js 函数,只能重新渲染返回。该功能是原子的,必须完成。这就是钩子(Hook)的用途。 React 控制钩子(Hook)何时运行,因此它可以做一些有趣的事情,比如批量状态更新,忽略过时的效果,并优先处理高优先级的工作,比如动画。

Compared to class components - shouldn't the code in the function body be equivalent to the constructor code in class components, and the return function - equivalent to the render method?

功能组件相当于类组件的render方法。它们以类似的方式被调用。所有其他生命周期方法都被钩子(Hook)取代。

我推荐 react docs是一个很好的起点,Dan Abramov 有一个 great deep dive on hooks .

关于reactjs - 需要更清楚的解释如何避免使用 React hooks 无限重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61512901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com