简体   繁体   English

React.memo 和 typescript

[英]React.memo and typescript

I am working on a react native app.我正在开发一个反应原生应用程序。 I am currently using Item component to display data in flatlist.我目前正在使用 Item 组件在 flatlist 中显示数据。 But editor gives me an error for the second parameter of React.memo like below.但是编辑器给了我一个 React.memo 的第二个参数的错误,如下所示。

Type 'boolean |输入'布尔| undefined' is not assignable to type 'boolean'. undefined' 不可分配给类型 'boolean'。

Type 'undefined' is not assignable to type '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;
        }
    }
);

Actually It expects the boolean to return so this might help实际上它希望 boolean 返回所以这可能会有所帮助

(prev, next) => {
   return prev.title === next.title;
 }
(prev, next) => { // error here
    if (prev.title === next.title) {
        return true;
    }
}

Typescript is expecting this function to return boolean . Typescript 期望这个 function 返回boolean But it only sometimes does.但它只是有时会。 If the condition is not satisfied, then no return statement is executed, which results in the function returning undefined .如果条件不满足,则不执行 return 语句,这导致 function 返回undefined And even though undefined is falsy, it is not the boolean value of false .即使undefined是假的,它也不是 boolean 的false值。

So to fix this, you need to make your function always return a boolean value on all conditional branches.因此,要解决此问题,您需要使您的 function 始终在所有条件分支上返回 boolean 值。

For example, you could add an else clause to your conditional that returns false .例如,您可以在返回false的条件中添加 else 子句。

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

Which should be simplified to just:应该简化为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM