为什么文档使用
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;
我认为这是一个不必要的优化。 至少在这个例子中。
记忆化不会带来性能提升,因为这些函数内部没有繁重的计算。
但是,当需要优化计算捕捉点或更改事件处理程序的繁重计算时,作者可能会使用它们作为可能的占位符。
这里有一个关于何时需要这些钩子的很好的解释。
在组件的开头创建 snapPoints 作为范围。
const snapPoints = useMemo(() => ['5%', '50%'], []);
然后将 snapPoints 作为 props 传递。
<BottomSheet ref={bottomSheetRef} onChange={handleSheetChanges} snapPoints={snapPoints}>
<BottomSheetView style={styles.contentContainer}>
<Text>Awesome 🎉</Text>
</BottomSheetView>
</BottomSheet>