You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React事件监听回调中三元运算符报错,if语句正常的原因咨询

为什么React事件回调里用三元运算符报错,用if语句却正常?

这个报错是ESLint的no-unused-expressions规则在起作用。

核心原因

三元运算符是表达式,它会生成一个返回值,但你在回调函数里直接写这个表达式却没有使用它的返回值,ESLint会认为这是一段无意义的代码,因此抛出Expected an assignment or function call and instead saw an expression错误。

而if是语句,它本身不产生返回值,只是用来执行条件逻辑,所以不会触发这条ESLint规则。

报错代码示例

import React, { useState } from "react";

const App = () => {
  const [count, setCount] = useState(0);

  const addCount = () => {
    setCount(count + 1);
  };

   const removeCount = () => {
    // 这里的三元表达式是未被使用的表达式,触发ESLint报错
    count > 0 ? setCount(count - 1) : null;
  };

  return (
    <>
      <h1>Counter : {count}</h1>
      <button onClick={addCount}>Add</button>
      <button onClick={removeCount}>Subtract</button>
    </>
  );
};

export default App;

正常运行的代码示例

import React, { useState } from "react";

const App = () => {
  const [count, setCount] = useState(0);

  const addCount = () => {
    setCount(count + 1);
  };

  const removeCount = () => {
    // if是语句,仅执行逻辑,不会触发ESLint规则
    if (count > 0) {
      setCount(count - 1);
    }
  };

  return (
    <>
      <h1>Counter : {count}</h1>
      <button onClick={addCount}>Add</button>
      <button onClick={removeCount}>Subtract</button>
    </>
  );
};

export default App;

解决方法

如果你想保留类似三元的简洁写法,可以用以下两种方式:

  • 用逻辑与运算符实现短路求值(ESLint默认允许这种写法):
    const removeCount = () => {
      count > 0 && setCount(count - 1);
    };
    
  • 把三元表达式的结果赋值给一个变量(虽然没必要,但能绕过ESLint检查):
    const removeCount = () => {
      const _ = count > 0 ? setCount(count - 1) : null;
    };
    

内容的提问来源于stack exchange,提问作者Opeyemi Ojo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 21:46:06