我需要幫助渲染我的數組我想在我的映射函數中創建一個條件。但不知何故,我transpiler不接受,並具有分析錯誤 這裏是我的代碼:如何使用jsx格式循環內部映射函數React JS
import { getGroups } from '../../actions/groupActions'
import { refreshToken } from '../../actions/authActions'
import { connect } from 'react-redux'
import _ from 'lodash'
import { Link } from "react-router"
class Group extends React.Component {
constructor(props) {
super(props);
this.state = {
groups: []
};
}
componentWillMount(){
this.props.getGroups().then(() => {
console.log('this groups props: ', this.props)
if(this.props.errors.code === 'UNAUTHORIZED'){
this.props.refreshToken().then(() => {
this.props.getGroups()
})
}
})
}
render(){
const groupArr = _.valuesIn(this.props.groups)
return (
<div>
<h1>Groups</h1>
<table className="table table-responsive table-bordered table-condensed">
<thead>
<tr>
<td>Name</td>
<td>Queue</td>
<td>Created At</td>
<td>Execution Type</td>
<td>Members</td>
<td>Action</td>
</tr>
</thead>
<tbody>
{this.props.groups ? (groupArr.map((groups, i) => {
return (
<tr key={i}>
<td>{groups.name}</td>
<td>{groups.queue}</td>
<td>{groups.createdAt}</td>
<td>{groups.executionType}</td>
<td>
{groups.members ? (groups.members.map((members, index) => {
{members.type === 'command' ? (
return (<div className="alert alert-success" role="alert" key={index}>{members._id}</div>)
) : (
return (<div className="alert alert-danger" role="alert" key={index}>{members._id}</div>)
) }
})) : (return ('No members found'))}
</td>
<td>
<Link className="btn btn-sm btn-warning" >
<i className="fa fa-pencil"></i>
</Link>
<button className="btn btn-sm btn-danger">
<i className="fa fa-trash-o"></i>
</button>
<button className="btn btn-sm btn-success">
<i className="fa fa-play-circle"></i>
</button>
</td>
</tr>
)
})) : (<tr>No records found</tr>)}
</tbody>
</table>
</div>
);
}
}
Group.propTypes = {
getGroups: React.PropTypes.func.isRequired,
errors: React.PropTypes.object.isRequired,
refreshToken: React.PropTypes.func
}
Group.contextTypes = {
router: React.PropTypes.object.isRequired
}
function mapStateToProps(state) {
return{
groups: state.groupReducer.groups,
links: state.groupReducer.links,
errors: state.groupReducer.errors
}
}
export default connect(mapStateToProps, { getGroups, refreshToken })(Group)
以下是錯誤:
SyntaxError: C:/Users/Frank/Projects/crun_fe/src/js/react/components/group/Group.js: Unexpected token (55:26) 53 | {groups.members ? (groups.members.map((members, index) => { 54 | {members.type === 'command' ? ( > 55 | return ({members._id}) | ^ 56 | ) : ( 57 | return ({members._id}) 58 | ) }
爲什麼你使用三元而不是正常的if語句。你已經在一個正常的功能。也作爲protip:不要發明函數內聯:給你的類正常的功能,然後有一個很好的,清晰的'render()'函數,其中包含...... ......{this.getGroupMembers()}。 .....' - 將盡可能多的代碼移動到渲染函數的* outside *之外,因爲將來 - 您將更好地保持當前代碼。 –
三元運算符與if語句的作用相同,但使用一個語句代碼,因此它減少了代碼行(LOC)。 –
當然,對任何必須維護你的代碼的人來說都是清楚的,除了用於任務之外,包括將來的你。這是正常的功能代碼,它應該在它自己的功能中,正常寫出來。 LOC是一種無意義的衡量標準,因爲它是2017年,我們有縮小版。當用戶從縮小的捆綁操作中獲得什麼時,您編寫的「代碼行數」爲零。 –