发布于 2026-01-06 1 阅读
0

避免在 React 和 Next.js 中使用不安全的“&&”运算符进行条件渲染。DEV 的全球展示挑战赛由 Mux 呈现:展示你的项目!

在 React 和 Next.js 中,避免使用不安全的“&&”运算符进行条件渲染。

由 Mux 赞助的 DEV 全球展示挑战赛:展示你的项目!

让我们来谈谈在使用 React 开发项目时我们都知道的一件事:条件渲染

在 React 中实现条件渲染时,有多种方法。开发者最喜欢的方法之一是使用&& 运算符

const Text = (isDisplayed) => {
  return (
    <div>
      // this one
      {isDisplayed && <p>{text}</p>}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

简单来说,如果条件为真,<p>则会显示一个包含特定文本的HTML元素;否则,根本不会渲染该元素。

但是,您是否检查过所有可能的真假值呢?如果没有,让我们来看看下面的结果!

// Truthy values

// boolean
{true && <p>😸</p>}

// number
{20 && <p>😸</p>}

// string
{"string" && <p>😸</p>}

// object
{{} && <p>😸</p>}

// array
{[] && <p>😸</p>}

// function
{(() => {}) && <p>😸</p>}

// symbol
{Symbol("symbol") && <p>😸</p>}

// All of them will render <p>😸</p> ✅
Enter fullscreen mode Exit fullscreen mode

到目前为止,我们还没有过多担心真值条件。但是现在,你有没有想过当条件为假时会发生什么?

// Falsy values

// null - this won't render anything ✅
{null && <p>😸</p>}

// undefined - this won't render anything ✅
{undefined && <p>😸</p>}

// boolean - this won't render anything ✅
{false && <p>😸</p>}

// NaN - this will render NaN 🤯 ❌
{NaN && <p>😸</p>}

// 0 - this will render 0 🤯 ❌
{0 && <p>😸</p>}

// negative 0 - this will render 0 🤯 ❌
{-0 && <p>😸</p>}

// string - this won't render anything ✅
{"" && <p>😸</p>}
Enter fullscreen mode Exit fullscreen mode

事实证明,并非所有假值都能给出预期的结果。这真是令人费解!🤯 这个问题经常在处理Notification Badge.

通知徽章

你可能觉得这是个小问题,但你猜怎么着?很多开发者根本就忘了用正确的方法处理它!

解决方案

幸运的是,我有一些解决这个问题的方法。

1. 转换condition为布尔值

// NaN
{Boolean(NaN) && <p>😸</p>}

// 0
{Boolean(0) && <p>😸</p>}

// negative 0
{!!-0 && <p>😸</p>}

// string
{!!"" && <p>😸</p>}

// All of them won't render anything ✅
Enter fullscreen mode Exit fullscreen mode

您可以使用Boolean(expression)函数或双重 NOT 运算符来处理这种情况!!expression。这些方法可以将任何数据类型转换为布尔值。如上面的结果所示,这两种方法在这种情况下true都能false正常工作。

2. 使用三元运算符

// NaN
{NaN ? <p>😸</p> : null}

// 0
{0 ? <p>😸</p> : null}

// negative 0
{-0 ? <p>😸</p> : null}

// string
{"" ? <p>😸</p> : null}

// All of them won't render anything ✅
Enter fullscreen mode Exit fullscreen mode

当条件为真时falsy,可以使用三元运算符返回null

结论

所以,如果我们牢记这些要点,就能避免很多麻烦,并提升代码质量。希望这篇文章能对你的项目有所帮助!✨

奖金

如果您已经安装了eslint-plugin-react,则可以启用以下规则。

{
  // ...
  "react/jsx-no-leaked-render": ["error", { "validStrategies": ["coerce"] }]
  // ...
}
Enter fullscreen mode Exit fullscreen mode

这样一来,ESLint 会自动将所有条件渲染代码替换为布尔值。

// From this ❌
{NaN && <p>😸</p>}

// To this ✅
{!!NaN && <p>😸</p>}
Enter fullscreen mode Exit fullscreen mode
文章来源:https://dev.to/maafaishal/avoid-operator-for-conditional-rendering-in-react-2de