首页 > 解决方案 > 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-native

解决方案


实际上是的,会发生重新渲染,因为 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.


推荐阅读