javascript - 为什么向我的 const 添加两个 if 语句会引发错误

标签 javascript reactjs meteor

我目前的 const 设置如下:

import React from 'react';
import { ButtonToolbar, Alert } from 'react-bootstrap';
import { CommentsModal } from '../comments-modal';


export const CommentsListBeijing = ({ comments }) => (
  comments.length > 0 ? <ButtonToolbar className="comment-list">
    {comments.map((com) => (
      <CommentsModal key={ com._id } comment={ com } city={com.city} person={com.person} location={com.location} title={com.title} content={com.content} fileLink={com.fileLink} timestamp={com.timestamp} createdBy={com.createdBy}/>
    ))}
  </ButtonToolbar> :
  <Alert bsStyle="warning">No sparks yet. Please add some!</Alert>
);

CommentsListBeijing.propTypes = {
  comments: React.PropTypes.array,
};

如果我想添加另一个 if 语句,我的代码会抛出错误。我不明白为什么。

这是我的新代码:

import React from 'react';
import { ButtonToolbar, Alert } from 'react-bootstrap';
import { CommentsModal } from '../comments-modal';

export const CommentsListBeijing = ({ comments }) => (
  if (comments.length > 0 ) {
    <ButtonToolbar className="comment-list">
    {comments.map((com) => (
      return com.adminSpark ? 
        /* something admin-related */ : 
        <CommentsModal 
          key={ com._id } 
          comment={ com } 
          city={com.city} 
          person={com.person} 
          location={com.location} 
          title={com.title} 
          content={com.content} 
          fileLink={com.fileLink} 
          timestamp={com.timestamp} 
          createdBy={com.createdBy} />
    ))}
    </ButtonToolbar> :
    <Alert bsStyle="warning">No sparks yet. Please add some!</Alert>
 );
CommentsListBeijing.propTypes = {
  comments: React.PropTypes.array,
};

当我现在尝试运行代码时,出现此错误:“imports/ui/components/beijing/comments-list-beijing.js:6:2: 意外的 token (6:2)”

第 6 行引用“if (comments.length > 0) {”

我做错了什么?

最佳答案

您在第一个示例中没有使用任何 if 语句。您正在使用ternary operator .

问题是,在第一个示例中,您只有一个表达式,因此箭头函数将隐式返回它的值。

当使用if时,您现在有一个语句

示例:

// Compiles just fine
var f = () => (
  (true) ? 1 : 0
);
// Could also write it as
// var f = () => true ? 1 : 0;
console.log(f());

// Will not compile
var f = () => (
  if (true) {
    return 1;
  } else {
    return 0;
  }
);
console.log(f());

您需要做的就是将箭头函数体括在大括号中。

// Now it works
var f = () => { // <--
  if (true) {
    return 1;
  } else {
    return 0;
  }
}; // <--
console.log(f());

关于javascript - 为什么向我的 const 添加两个 if 语句会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41026412/

相关文章:

javascript - 为什么不能使用 "switch"技术从 HTML 更改范围值?

reactjs - 为 typescript 的 npm react 模块定义类型

reactjs - 如何在库组件和我的应用程序组件之间共享上下文?

mongodb - 如何识别 meteor 内运行的minimongo的端口?

javascript - Ajax .done() 不适合我

javascript - 循环数据属性并设置对应的输入值

javascript - 使用 useCallback/useMemo 卡住闭包

javascript - meteor - preventDefault 不阻止默认

meteor - 引用错误: is not defined

javascript - bootstrap.js 中的 emulateTransitionEnd,它来自哪里?