如何解决“重新渲染次数过多”的问题在功能组件中使用回调?
我有一个功能组件,例如
function Blurg(props) {
const [state, setState] = useState(..);
const callback = (data) => { .. setState(...) }
somethingExternal.addListener(callback);
return ...
}
如果存在值,将立即调用回调。
(编辑:该值将保留,因此每次附加侦听器时,它都会立即收到该值。)
但这会导致错误“重新渲染次数过多”,因为状态已更改,然后再次调用功能组件(我猜),再次添加监听器等等。
如何解决这个问题?
I have a functional component like
function Blurg(props) {
const [state, setState] = useState(..);
const callback = (data) => { .. setState(...) }
somethingExternal.addListener(callback);
return ...
}
where the callback will be called immediately if there is a value present.
(Edit: the value will stay, so each time a listener is attached it receives that value immediately.)
But this leads to an error saying "Too many re-renders", because the state is changed, then the functional component is called again (i guess), adding the listener again and so forth.
How to resolve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这样的一次性效果解决了这个问题
使用像Explanation
useEffect
的第二个参数是一个依赖项列表,当更改时,将触发重新评估效果。因此,如果传递一个空的依赖项列表,则不会发生任何变化。
Solved it using a one-time effect like
Explanation
The second argument of
useEffect
is a list of dependencies, that - when changed - will trigger the effect to be re-evaluated.Thus, if passed an empty list of dependencies, nothing will change.