我有一个很奇怪的问题,我有两个组件(两个导航路径),它们共享相同的高阶组件,使帖子保持状态。 一个组件可以通过将后塞子传递到路线作为参数来链接到另一个组件,该组件又将flaList滚动到正确的索引:
findIndexBySlug = memoizeOne(
(postsArray, selectedPostSlug) => postsArray.findIndex(
post => post.slug === selectedPostSlug,
),
);
constructor(props) {
super(props);
this.shouldScrollToPost = this.shouldScrollToPost.bind(this);
this.scrollToIndex = this.scrollToIndex.bind(this);
this.flatListRef = React.createRef();
}
componentDidMount() {
this.shouldScrollToPost();
}
componentDidUpdate() {
this.shouldScrollToPost();
}
shouldScrollToPost() {
const { navigation } = this.props;
const selectedPostSlug = navigation.getParam('selectedPostSlug');
console.log('shouldscrollto', selectedPostSlug);
if (selectedPostSlug) {
const { posts } = this.props;
const { postsArray } = posts;
const selectedPostIndex = this.findIndexBySlug(
postsArray, selectedPostSlug,
);
this.scrollToIndex(selectedPostIndex);
}
}
scrollToIndex(index) {
if (this.flatListRef.current) {
console.log('scrolling to ', index)
this.flatListRef.current.scrollToIndex({ index, animated: false });
}
}
在第一次挂载(componentDidMount)和后续调用(componentDidUpdate)中,所有console.log都会触发(包括检查flatListref的控制台),但是,当第一次在componentDidMount中调用时,没有滚动发生,因此在componentDidUpdate中实际滚动!
为什么?
这让我发疯,甚至读了Dan Abramov上关于引用(componentDidMount called BEFORE ref callback)的可用性的信息,并且flatList是唯一呈现的组件(实际上,引用始终可用)。
任何帮助表示赞赏。
谢谢