只要 animationType
或 animationComplete
的值发生变化,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/