我目前的 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/