Flatlist完成渲染后,调用scrolToEnd

时间:2020-09-28 14:16:06

标签: react-native react-native-flatlist flatlist

我有一个聊天应用程序,该应用程序使用留言列表。这个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吗?

0 个答案:

没有答案
相关问题