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

React 18.0中JSX三元运算符条件渲染state值报错问题

问题根因

报错是JSX表达式写法错误导致的:

  • JSX里只用最外层一对{}标记要插入的JavaScript表达式边界,括号里直接写合法JS代码就行,计算结果会交给React渲染。
  • 出问题的第三个h3里,三元表达式的两个返回值多套了一层{}。这层大括号在JS执行上下文里会被当成对象字面量解析:首先{points.playerOne}本身就不符合JS对象语法(点操作符不能直接写在对象字面量的属性定义位置),其次你要渲染的是分数数值,根本不需要包装成对象。
  • 你写的第二个h3能正常渲染,就是因为三元分支直接返回1、2字面量,没多套大括号,写法是对的。
修复方案

把三元表达式两个分支外面多余的大括号删掉,直接返回对应的状态值就行,修复后的对应代码:

<h3> points of player one is {state === true ? points.playerOne : points.playerTwo} </h3>

完整可运行的组件代码:

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [points, setPoints] = useState({ playerOne: 0, playerTwo: 0 });
  const [state, setState] = useState(true);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h3> value is {points.playerOne} & {points.playerTwo} </h3>
      <h3> points of player one is {state === true ? 1 : 2} </h3>
      <h3> points of player one is {state === true ? points.playerOne : points.playerTwo} </h3>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 13:36:15