首页 > 解决方案 > 内置的 react 原生组件是纯的吗?

问题描述

我在文档中发现Flatlist,SectionListPureComponents. 没有关于其他组件的任何信息(例如TouchableOpacity)。我想找出哪个 RN 内置组件useCallback在必要时可以使用。

如果所有其他组件都不是纯的,则无需useCallback在此示例中使用。

export default App = () => {
  const [count, setCount] = useState(0);
  const onPress = useCallback(() => setCount(prevCount => prevCount + 1), [prevCount]);

  return (
    <View style={styles.container}>
      <TouchableOpacity
        style={styles.button}
        onPress={onPress}
      >
        <Text>Press Here</Text>
      </TouchableOpacity>
    </View>
  );
};

标签: react-nativereact-hooks

解决方案


TL;DR Flatlist, SectionList, VirtualizedListReact.PureComponent其余组件是React.Component.

如何查找哪个组件正在使用 PureComponent

你可以在 Github 上查看 react-native 组件的源代码,无论它们是使用 PureComponent 还是普通组件。

你看到 React-Native 的 TouchableOpacity 是用 Component 扩展的。

TouchableOpacity 源

在此处输入图像描述

但另一方面,you can see FlatList uses PureComponent

平面列表源

在此处输入图像描述

此外,您可以看到SectionList用于React.PureComponent

部分列表源

在此处输入图像描述

这是Text component of React-Native哪个is not using React.PureComponent

文字来源

在此处输入图像描述

因此,结论是默认情况下,每个组件都会扩展,React. Component不包括他们在他们正在使用的文档中提到的那些组件React.PureComponent

在哪里使用 useCallback 钩子

used to optimizing rendering of a class component如您所知,如果您想优化功能组件,那么纯组件是这样的吗?

you can use React.memo

当将回调传递给依赖引用相等性以防止不必要的渲染(例如 shouldComponentUpdate)的优化子组件时,useCallback 很有用。

Learn about when to use memo or useCallback阅读这篇有趣的文章。

https://kentcdodds.com/blog/usememo-and-usecallback


推荐阅读