【问题标题】:Can't use if statement inside const declaration, but ternary operator works [duplicate]不能在 const 声明中使用 if 语句,但三元运算符有效[重复]
【发布时间】:2019-10-30 01:17:41
【问题描述】:

我正在浏览一些编码示例,并遇到了 React 中组件声明的一个示例:

export const TodoList = ({ todos }) => (
    <ul>
        {
            todos && todos.length
            ? todos.map((todo, index) => {
                return <Todo key={`todo-${todo.id}`} todo={todo} />
            })
            : "No todos, yay!"
        }
    </ul>
);

我想尝试将这个三元运算符转换为 if/else 语句,如下所示:

export const TodoList = ({ todos }) => (
    <ul>    
        {
            if (todos) && (todos.length) {
                todos.map((todo, index) => {
                    return <Todo key={`todo-${todo.id}`} todo={todo} />
                })
            } else {
                "No todos, yay!"
            }
        }
    </ul>
);

但是,我在if 语句开始的那一行得到错误:

解析错误:意外的令牌

为什么三元运算符在这里有效,而 if 语句却无效?

【问题讨论】:

  • {…} 包装一个表达式,如2 + 2x ? y : z。 if 语句是语句,而不是表达式。
  • 啊..我不知道这个。谢谢
  • 无论如何它必须是if (todos &amp;&amp; todos.length)。括号是if 语法的一部分。

标签: javascript reactjs ecmascript-6


【解决方案1】:

{}s 之间的内容必须是表达式。条件(三元)运算符的计算结果为表达式;另一方面,if 是一个不能作为表达式求值的语句。出于类似的原因,这是无效的:

const foo = if (true) {
  'bar'
}

If-Else in JSX:

if-else 语句在 JSX 中不起作用。这是因为 JSX 只是函数调用和对象构造的语法糖。举个基本的例子:

// This JSX:
ReactDOM.render(<div id="msg">Hello World!</div>, mountNode);

// Is transformed to this JS:
ReactDOM.render(React.createElement("div", {id:"msg"}, "Hello World!"), mountNode);

这意味着 if 语句不适合。举个例子:

// This JSX:
<div id={if (condition) { 'msg' }}>Hello World!</div>

// Is transformed to this JS:
React.createElement("div", {id: if (condition) { 'msg' }}, "Hello World!");

【讨论】:

    【解决方案2】:

    if 语句是流控制,而三元运算符是简单的运算符。 if 语句需要代码,三元运算符需要值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-01
      • 2017-11-19
      • 2020-03-13
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 2018-12-08
      • 2019-12-30
      相关资源
      最近更新 更多