【发布时间】:2020-05-06 19:24:03
【问题描述】:
我有一个图标组件,它绘制一个图标并且它正在闪烁,因为父级正在让它重新渲染。我不明白为什么会发生这种情况以及如何防止这种情况发生。
Here is a snack 显示问题。
我们使用 setInterval 模拟父级更改。
我们通过在控制台中记录“重新渲染”来模拟图标重新渲染。
代码如下:
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
// or any pure javascript modules available in npm
let interval = null
const Child = ({name}) => {
//Why would this child still rerender, and how to prevent it?
console.log('rerender')
return <Text>{name}</Text>
}
const ChildContainer = ({name}) => {
const Memo = React.memo(Child, () => true)
return <Memo name={name}/>
}
export default function App() {
const [state, setState] = React.useState(0)
const name = 'constant'
// Change the state every second
React.useEffect(() => {
interval = setInterval(() => setState(s => s+1), 1000)
return () => clearInterval(interval)
}, [])
return (
<View>
<ChildContainer name={name} />
</View>
);
}
如果你能解释一下为什么会发生这种情况以及解决它的正确方法是什么,那就太棒了!
【问题讨论】:
-
你的父组件是否不断发生一些变化?
-
我们改变onMouseEnter和onMouseLeave的状态。这会使图标闪烁
标签: reactjs react-native react-hooks