如何正确检测React JS中的rerender? [英] How to detect rerenders in React JS correctly?

查看:81
本文介绍了如何正确检测React JS中的rerender?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我们有一个父组件和多个功能子组件.我想清楚地知道,父母是否要重新渲染孩子是否要重新渲染.

浏览了几篇文章后,我知道有3种方法可以检测到重新渲染.(让我知道是否还有更多方法.)

1.在子组件中放入 console.log .

2.在设置中使用"Chrome涂料闪烁"选项.

3.使用React开发工具

所有这些方法是否正确,才能知道该组件是否真的退货了?因为它似乎不能与React.memo一起正常工作.

当我用React.memo包装子组件时,当父组件重新发布时,它不会打印 console.log .但是仍然使用chrome和react开发工具可以突出显示子组件,就像重新渲染一样.

CodeSandbox:

之后

结论

console.log react-dev-tools 都运作良好,您可能只需要按照自己的需求以适当的方式实施即可.

Let's say we have a parent component and multiple functional child components. I want to clearly know if the parent re-renders does the child re-renders or not.

After going through a few articles I came to know there are 3 ways we can detect rerenders. (Let me know if there are more ways.)

1. Put a console.log in the child component.

2. Use Chrome paint flashing option in the settings.

3. Use React dev tool

Do all these ways are correct to know if the component really rerenders? Because it doesn't seem to be work correctly with React.memo.

When I am wrapping the Child component with React.memo it does not print console.log, when the parent component rerenders which is correct. But still with chrome and react dev tools highlights the child component as if it rerendered.

CodeSandbox: https://codesandbox.io/s/bold-cloud-iv0rv (If we add a new car still the static component is highlighted in green, but as per Memo, it should not rerender.)

Now my doubt, Is paint flashing does not work correctly or React.memo having issues?

解决方案

Reason

If you use React.memo, you need to use it from parent down to all the child till the end.

Since React.PureComponent share the same feature with React.memo, you can find those explanation in the document as below.

Furthermore, React.PureComponent’s shouldComponentUpdate() skips prop updates for the whole component subtree. Make sure all the children components are also "pure".

Result

By changing parent component Cars to memo

// Before
export default Cars;
// After
export default React.memo(Cars);

You could find the react-dev-tools in chrome will only show the parent component re-rendered this time as well as no child console.log fired, which is correct. (Compare to previous, all the child also got highlighted)

Before

After

Conclusion

Both console.log and react-dev-tools worked well, you may just need to implement in a proper way following your demand.

这篇关于如何正确检测React JS中的rerender?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆