【问题标题】:React.memo and typescriptReact.memo 和打字稿
【发布时间】:2020-12-05 09:02:31
【问题描述】:

我正在开发一个反应原生应用程序。我目前正在使用 Item 组件在 flatlist 中显示数据。但是编辑器给了我一个 React.memo 的第二个参数的错误,如下所示。

键入'布尔值| undefined' 不能分配给类型 'boolean'。

类型“未定义”不可分配给类型“布尔”。

const Item = React.memo(
    ({ icon, title }: any) => {
        return (
            <Box
                flexDirection="row"
                paddingHorizontal="l"
                justifyContent="space-between"
                alignItems="center"
                style={{ marginTop: 35 }}
            >
                <Box flexDirection="row" alignItems="center" flex={1}>
                    {icon}

                    <Box marginLeft="l">
                        <Text  variant="stackHeader">{title}</Text>
                        <Text
                            fontSize={15}
                            fontFamily="CrimsonRegular"
                            style={{ color: '#575757' }}
                        >
                            Last update: 03/06/2020
                        </Text>
                    </Box>
                </Box>
                <TouchableOpacity onPress={() => Clipboard.setString(title as string)}>
                <FontAwesome5 name="copy" size={28} color="white" />
                </TouchableOpacity>
            </Box>
        );
    },
    (prev, next) => { // error here
        if (prev.title === next.title) {
            return true;
        }
    }
);

【问题讨论】:

  • 在 if 条件之后是否需要返回 false 才能返回布尔值
  • 我添加了其他条件并且它有效。感谢您的帮助

标签: typescript react-native react-memo


【解决方案1】:
(prev, next) => { // error here
    if (prev.title === next.title) {
        return true;
    }
}

Typescript 期望此函数返回 boolean。但它只是有时会。如果条件不满足,则不执行 return 语句,从而导致函数返回 undefined。即使undefined 是假的,它不是false 的布尔值。

所以要解决这个问题,你需要让你的函数在所有条件分支上总是返回一个布尔值。

例如,您可以在返回 false 的条件中添加 else 子句。

(prev, next) => {
    if (prev.title === next.title) {
        return true;
    } else {
        return false;
    }
}

应该简化为:

(prev, next) => {
    return prev.title === next.title
}

【讨论】:

    【解决方案2】:

    实际上它希望布尔值返回,所以这可能会有所帮助

    (prev, next) => {
       return prev.title === next.title;
     }
    

    【讨论】:

      猜你喜欢
      • 2019-04-25
      • 2018-12-25
      • 2021-08-08
      • 2016-02-06
      • 2014-01-23
      • 1970-01-01
      • 2014-07-04
      • 2019-10-28
      • 2021-11-29
      相关资源
      最近更新 更多