'||' 的意外混合和 '&&' 非混合运算符

时间:2021-02-09 09:08:36

标签: reactjs pusher-js

我有以下钩子,我们用它来绑定到频道。

import { useEffect, useState } from "react";
import { Channel, PresenceChannel } from "pusher-js";
import PrivateChannel from 'pusher-js/types/src/core/channels/private_channel';
import { usePusher } from "./usePusher";

export type ChannelType = PrivateChannel | PresenceChannel

function _useChannel<T extends ChannelType>(channelName: string) {
    const pusher = usePusher()
    const [channel, setChannel] = useState<T>();

    useEffect(() => {
        const pusherChannel = pusher.subscribe(channelName) as T;
        setChannel(pusherChannel);

        return () => pusher?.unsubscribe(channelName);
    }, [channelName, pusher]);

    return channel;
}

当我打开控制台时,我看到以下消息:Unexpected mix of '||' and '&&' no-mixed-operators

为什么会发生这种情况?

1 个答案:

答案 0 :(得分:1)

正如@Drew Reese 所说,您在某处有一个复杂的逻辑表达式混合 &&||,并且您已配置 ESLint 以在发生这种情况时向您发出警告。您必须找到发生这种情况的地方,并添加必要的括号以阐明您的意图。

来自ESLint docs

var foo = a && b || c || d;    /*BAD: Unexpected mix of '&&' and '||'.*/
var foo = a && b ? c : d;      /*BAD: Unexpected mix of '&&' and '?:'.*/
var foo = (a && b) ? c : d;    /*GOOD*/
var foo = (a && b) || c || d;  /*GOOD*/
var foo = a && (b || c || d);  /*GOOD*/

如果您不确定布尔运算符的正确优先级应该是什么,请认为 && 可以被认为是 multiplication 的等价物,而 ||addition,因此 && 优先于 ||

例如:

a && b || c || d 
<=> a*b + c + d 
<=> (a && b) || c || d