代码之家  ›  专栏  ›  技术社区  ›  j.doe BudgieInWA

为什么我的组件在道具更改时重新渲染?

  •  0
  • j.doe BudgieInWA  · 技术社区  · 7 年前

    无论何时 animationType animationComplete 更改后,Splash组件将重新呈现。我不明白为什么当没有道具传递到渲染器时它会重新渲染。

    export class Splash extends React.Component {
        static propTypes = {
            animationType: allowNullPropType(PropTypes.string),
            animationComplete: PropTypes.bool,
            changeAnimation: PropTypes.func
        };
    
        componentDidMount() {
            const {changeAnimation} = this.props;
    
            // ...
        }
    
        componentDidUpdate() {
            const {animationType, animationComplete} = this.props;
            const shouldChangeScreen = (animationType === 'out' && animationComplete);
    
            if (shouldChangeScreen) {
                const {navigation} = this.props;
    
                // ...
            }
        }
    
        render() {
            return (
                <Fade id='splash' styles={styles.container}>
                    <Logo height='125' width='125'/>
                </Fade>
            );
        }
    }
    
    const mapStateToProps = (state) => {
        return {
            animationType: state.fade.getIn(['splash', 'type']),
            animationComplete: state.fade.getIn(['splash', 'complete'])
        }
    };
    
    const mapDispatchToProps = (dispatch) => {
        return {
            changeAnimation: (id, type) => dispatch(changeAnimation(id, type))
        }
    };
    
    export default connect(mapStateToProps, mapDispatchToProps)(Splash);
    

    我尝试用一个简单的视图组件替换Fade(它也连接到Redux store和dispatches actions)和Logo组件,但问题仍然存在。我也试过使用重新选择。

    shouldComponentUpdate() {
            return false;
        }
    

    但这似乎不是一个很好的解决方案。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Maggie    7 年前

    这就是react的工作原理。道具中的任何更改都将导致组件再次调用render方法,除非使用shouldComponentUpdate阻止它。

        2
  •  0
  •   gazdagergo    7 年前

    您应该始终认为“render”在React中表示“render the virtual DOM”。实际的DOM部分只有在发生了真正的变化时才会被重新呈现。所以不用担心大量渲染。