0

我正在开发一个反应原生应用程序。我目前正在使用 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;
        }
    }
);
4

2 回答 2

1

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

(prev, next) => {
   return prev.title === next.title;
 }
于 2020-12-05T09:09:57.903 回答
1
(prev, next) => { // error here
    if (prev.title === next.title) {
        return true;
    }
}

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

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

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

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

应该简化为:

(prev, next) => {
    return prev.title === next.title
}
于 2020-12-05T09:25:33.143 回答