我正在使用getDerivedStateFromProps
,并且只想在children
不同的情况下更新状态。我的实现如下所示:
在我的组件中:
class PageTransition extends Component {
constructor(props) {
super(props);
const { children } = this.props;
this.state = {
children,
fadeOut: false,
};
}
static getDerivedStateFromProps(nextProps, prevState) {
const hasNewChildren = childrenAreDifferent(nextProps.children, prevState.children);
if (hasNewChildren) return { fadeOut: true };
return null;
}
render() {
const { fadeOut } = this.state;
return (
<Wrapper fadeOut={fadeOut}>
{children}
</Wrapper>
);
}
}
childrenAre不同的助手:
export default (oldChildren, newChildren) => {
// Children are the same
if (oldChildren === newChildren) return false;
// Children are react elements with equal keys
if (
React.isValidElement(oldChildren)
&& React.isValidElement(newChildren)
&& oldChildren.key != null
&& oldChildren.key === newChildren.key
) {
return false;
}
// Children are different
return true;
};
问题在于oldChildren.key会以null形式出现,因此我的助手功能无法正常工作。 key
是在所有情况下都能比较此类儿童的可靠方法吗?还是有更好的方法?我应该如何编写上面的辅助函数?