react-native - View 已经是 react native 中的纯组件了吗?
问题描述
在 React Native 中,说我有类似的东西
var styles = { ... }
export default class App extends React.Component {
...
render() {
return(
<View style={styles.container}>
<View style={{width: this.state.widthA}} />
<View style={{width: this.state.widthB}} />
</View>
);
}
}
当状态widthA
改变时,render() 函数会再次被调用。同级视图(widthB)也会重新渲染吗?是否有任何性能提升需要定义
class PureView extends React.PureComponent {
constructor(props) {
super(props);
}
render() {
return <View {...this.props} />
}
}
并用 PureView 替换两个视图?
解决方案
实际上是的,会发生重新渲染,因为 react 中的重新渲染属于两件事。
1. The props of the parent is changed.
2. The state of a component changed.
因此,在您的情况下,组件的状态正在发生变化,这就是为什么您的兄弟姐妹也会重新渲染,因为这两个兄弟姐妹的父级状态已更改。
为了避免这种情况,有两个这样做。
1. Use Pure component
纯组件查看前一个状态和下一个状态并巧妙地处理您的重新渲染,但纯组件并非在每种情况下都适用或有用。
2. ShouldComponentUpdate
此方法用于手动处理重新渲染,就像在您的情况下您不想重新渲染您的第二个兄弟姐妹一样,因此您可以根据兄弟姐妹的生命周期方法中的道具返回 false,因此该组件不会重新通过此更改呈现。
The View is just a UI container re-rendering depends on component props or state, So View can't control the re-render of a component
.
推荐阅读
- c++ - 如何知道内存分配器中项目的父块
- c# - 未分配的局部变量并将 char 转换为字符串
- bash - 如何在bash中提取变量的IP部分
- php - 除一种情况外的内连接
- javascript - 如何检查 JavaScript 中是否存在具有特定类的 html 元素?
- c++ - 将 MEX (MATLAB) 与 Eigen 和英特尔 MKL 链接
- libreoffice - 在创建带有少量参数的下拉列表后在单元格中换行
- c# - 用扭矩应用偏航旋转会导致物体在倒置时不断旋转(fzero like)
- python - 如何检查一个项目是否存在于多维 numpy 数组中?
- css - 如何在带有 JSS 的 typescript react-app 中使用谷歌字体?