为什么snapPoints用useMemo来记忆react-native-bottom-sheet

问题描述 投票:0回答:2

为什么文档使用

useCallback
useMemo
来记住为
BottomSheet
传递的 props,这样做的性能优势是什么?

https://gorhom.github.io/react-native-bottom-sheet/usage

import React, { useCallback, useMemo, useRef } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import BottomSheet from '@gorhom/bottom-sheet';

const App = () => {
  // ref
  const bottomSheetRef = useRef<BottomSheet>(null);

  // variables
  const snapPoints = useMemo(() => ['25%', '50%'], []);

  // callbacks
  const handleSheetChanges = useCallback((index: number) => {
    console.log('handleSheetChanges', index);
  }, []);

  // renders
  return (
    <View style={styles.container}>
      <BottomSheet
        ref={bottomSheetRef}
        index={1}
        snapPoints={snapPoints}
        onChange={handleSheetChanges}
      >
        <View style={styles.contentContainer}>
          <Text>Awesome 🎉</Text>
        </View>
      </BottomSheet>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 24,
    backgroundColor: 'grey',
  },
  contentContainer: {
    flex: 1,
    alignItems: 'center',
  },
});

export default App;
react-native react-usememo react-usecallback
2个回答
2
投票

我认为这是一个不必要的优化。 至少在这个例子中。

记忆化不会带来性能提升,因为这些函数内部没有繁重的计算。

但是,当需要优化计算捕捉点或更改事件处理程序的繁重计算时,作者可能会使用它们作为可能的占位符。

这里有一个关于何时需要这些钩子的很好的解释。

https://www.joshwcomeau.com/react/usememo-and-usecallback/


0
投票

在组件的开头创建 snapPoints 作为范围。

const snapPoints = useMemo(() => ['5%', '50%'], []);

然后将 snapPoints 作为 props 传递。

<BottomSheet ref={bottomSheetRef} onChange={handleSheetChanges} snapPoints={snapPoints}>
    <BottomSheetView style={styles.contentContainer}>
      <Text>Awesome 🎉</Text>
    </BottomSheetView>
  </BottomSheet>
© www.soinside.com 2019 - 2024. All rights reserved.