如何解决Flatlist完成渲染后,调用scrolToEnd
我有一个聊天应用程序,该应用程序使用留言列表。这个FlatList需要在两个方向上无限加载(以查看较旧的消息或较新的消息)。
由于maintainVisibleContentPosition
道具在Android上不起作用,因此我不得不组合一个黑客程序,以便能够加载内容而不会丢失屏幕上的内容。
- 如果用户到达聊天顶部,则将Flatlist设置为反向-> scrollToEnd(屏幕顶部)->加载较旧的消息
- 如果用户到达了聊天底部,则将Flatlist设置为“普通”->“ scrollToEnd”(屏幕底部)->“加载更多最新消息”
我使用useEffect
来检测inverted
的值何时更改为调用scrollToEnd
并加载其余值。我的代码的简化版本以说明其工作方式:
const [useInverted,setuseInverted] = React.useState(false);
const [reversing,setreversing] = React.useState(false);
const loadTop = React.useCallback(() => {
if (!useInverted) {
setuseInverted(true);
setreversing(true);
} else {
// Load old messages
}
},[useInverted]);
const loadBottom = React.useCallback(() => {
if (useInverted) {
setuseInverted(false);
setreversing(true);
} else {
// Load recent messages
}
},[]);
React.useEffect(() => {
// Should be called after FlatList rerendered completely
if(reversing){
flatlist.current.scrollToEnd({ animated: false }); // <--- THIS doesn't work. List stays at start
if (useInverted) {
loadTop();
}else{
loadBottom();
}
}
},[useInverted,loadBottom,loadTop ]);
return (
<FlatList
key={string(useInverted)} // Changing the key of the flatlist otherwise it doesn't update
inverted={useInverted}
// ...other props + logic to call loadTop and loadBottom
/>
)
我的问题是useEffect似乎被调用为时过早,scrollToEnd
没有执行任何操作。仅当我在任意延迟后使用setTimeout()来调用scrollToEnd
时,它才起作用。
有什么方法可以检测FlatList完成重新渲染的时间,并且可以安全地调用scrollToEnd
吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。