无法在 JSX 中使用三元运算符嵌入重定向

Unable to Embed redirect using Ternary operator in JSX

我使用的是 Firefox 83.0 我正在尝试使用 React 编写一个基本的重定向,但每次我使用 turnery 运算符时,我都会收到一条错误消息,表明我正在使用意外标记“,”代替“[=” 16=]?"

您可以在下面的截图中看到错误和相关代码

I haven't provided the complete code because I don't think it is relevant in this case but do let me know if the code is required

问题不是 JSX,而是 JS 语法。查看您的代码中发生了什么:

  1. 你有一个 return 跟在 ( 之后,这是有效的 JS 代码
  2. 然后你打开了一个{,它告诉JS引擎一个对象即将被创建。 对象结构为 {key: value}.

所以发生的事情是 JS 引擎告诉您创建对象的语法错误。

你应该只省略大括号 { 就可以正常工作了

return (
   redirect ? <Redirect /> : the rest of the code
)

如果您在 JSX 标记中使用它,那将是有效代码。

<div>{isValid ? 'yes': 'no'}</div>

在这里你告诉编译器,你想在 JSX 中编写 JS 代码