【问题标题】:How to fix 'eslint-disable-next-line react/no-unstable-nested-components'如何修复 \'eslint-disable-next-line react/no-unstable-nested-components\'
【发布时间】:2022-08-04 01:44:38
【问题描述】:

我的 react-native typescript 项目中有以下代码 sn-p。

import React from \'react\';
import { View, Text } from \'react-native\';

import DropDownPicker from \'react-native-dropdown-picker\';

const Dropdown = () =>{
  <DropDownPicker
    ArrowDownIconComponent={() => ( // this is the section I getting the error message
      <MaterialCommunityIcons
        name=\"home-outline\"
        size={50}
        color={theme.colors.text}
      />
    )}
  />
}

由于 es-lint,它给出了以下错误消息:

错误信息:

在父组件 \"DropDown\" 之外声明这个组件或 memoize 它。如果要允许在 props 中创建组件,请设置 allowAsProps true.eslintreact/no-unstable-nested-components 的选项

错误图片:enter image description here

请问我可以知道如何解决上述错误吗?

    标签: react-native typescript-eslint


    【解决方案1】:

    只需在父组件之外声明组件:

    
    const ArrowDownIconComponent = () => (
      <MaterialCommunityIcons
        name="home-outline"
        size={50}
        color={theme.colors.text}
      />
    );
    
    const Dropdown = () =>{
      <DropDownPicker
        ArrowDownIconComponent={ArrowDownIconComponent}
      />
    }
    

    或者,如果themeDropdown 组件的状态变量,请记住它:

    const Dropdown = () =>{
    
      const theme = useTheme();
    
      const ArrowDownIconComponent = useMemo(() => (
        <MaterialCommunityIcons
            name="home-outline"
            size={50}
            color={theme.colors.text}
          />
      ), [theme.colors.text])
    
      return (
        <DropDownPicker
          ArrowDownIconComponent={ArrowDownIconComponent}
        />
      );
    }
    

    解释

    每当状态更改时,ArrowDownIconComponent 都会重新声明并重新渲染

    ArrowDownIconComponent 仅声明一次(或仅在 theme.colors.text 更改时重新声明),因此会提高一些性能。

    【讨论】:

    • 我需要澄清一下,如果我需要将道具传递给我们在外部创建的组件(ArrowDownIconComponent)怎么办?
    • 同样的规则适用于 props,如果它不依赖于父状态,则将其声明为 const。如果它依赖于某些父状态,请记住它。 @安娜弗莱彻
    • 你通过: const ArrowDownIconComponent = (props) =>... 而在组件内部: <DropDownPicker ArrowDownIconComponent={() => ArrowDownIconComponent(props)} />
    【解决方案2】:

    我太菜鸟了,不知道为什么,但useMemo 对我不起作用。在我的情况下,我不得不使用useCallback,看起来像

    const Dropdown = () =>{
    
      const theme = useTheme();
    
      const ArrowDownIconComponent = useCallback(() => (
        <MaterialCommunityIcons
            name="home-outline"
            size={50}
            color={theme.colors.text}
          />
      ), [theme.colors.text])
    
      return (
        <DropDownPicker
          ArrowDownIconComponent={ArrowDownIconComponent}
        />
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      • 2020-02-17
      • 2019-01-20
      • 1970-01-01
      • 2020-06-13
      相关资源
      最近更新 更多