javascript - 为什么当 prop 更改时我的组件会重新渲染?

标签 javascript reactjs react-native redux

只要 animationTypeanimationComplete 的值发生变化,Splash 组件就会重新渲染。我不明白为什么当没有 Prop 传递到渲染中时它会重新渲染。

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);

我尝试用简单的 View 组件替换 Fade(它也连接到 Redux 存储并调度操作)和 Logo 组件,但问题仍然出现。我也尝试过使用重新选择。

唯一有效的解决方案是:

shouldComponentUpdate() {
        return false;
    }

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

最佳答案

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

关于javascript - 为什么当 prop 更改时我的组件会重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51816910/

相关文章:

reactjs - 如何将 {key, value} 的通用有效负载输入到接口(interface)的特定属性?

reactjs - react 上下文 : Provide instance of an Api Manager

javascript - 将用户数据从一个屏幕传递到另一个屏幕 - React Native

javascript - Firefox 的图像加载失败,但 Chrome、Edge 和 IE 运行良好

javascript - 调整 Fabricjs 矩形的大小以保持边框大小

javascript - Google map 标记图标未加载(ReferenceError : google is not defined))

reactjs - react-router basename 无法正常工作

javascript - 如何从项目列表中选择 ScrollView 中的中心项目

javascript - 在平面列表中 react native 导航

javascript - 页面刷新后淡入 div