如何在同一代码行中使用map()和find()

时间:2018-08-15 08:28:33

标签: javascript reactjs

我有2个文件,例如在示例中:

player.js-现在,我仅在对象中使用一项

const players = {
  playerId: '5555',
  playerName: 'JHON',
  playerTeams: [real, barcelona, liverpol],
};

Team.js

const Teams = [
  { name: 'real', teamImageSrc: '' },
  { name: 'barcelona', teamImageSrc: '' },
  { name: 'liverpol', teamImageSrc: '' },
];

在项目的这个阶段,我的目的是检查我的UI代码是否能正确显示数据,稍后我将更正UI背后的逻辑,现在我想做的是显示以下内容的列表:团队成员是该玩家的成员,我已经使用map()设法完成了此任务,但我需要找到从map()获得的每个值的图像,如下例所示:

class GridPlayerTeamsMembership extends React.Component {
  render() {
    const { classes } = this.props;

    return (
      <div className={classes.root}>
        <List>
          {players.playerTeams.map(value => (
            <ListItem dense button className={classes.listItem}>
              <Avatar ? />
              <ListItemText primary={` ${value}`} />
            </ListItem>
          ))}
        </List>
      </div>
    );
  }
}

GridPlayerTeamsMembership.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(GridPlayerTeamsMembership);

2 个答案:

答案 0 :(得分:4)

您可以创建如下函数:

teamImage = (teamName) => Teams.find(t=>t.name===teamName).teamImageSrc

并像这样使用teamImage:

<Avatar src={this.teamImage(value)} />

答案 1 :(得分:0)

好的,我成功了,但是没有这个。

class GridPlayerTeamsMembership extends React.Component {

render() {
const { classes } = this.props;
teamImage = (teamName) => Teams.find(t=>t.name===teamName).teamImageSrc

return (
      <div className={classes.root}>
        <List>
          {players.playerTeams.map(value => (
            <ListItem key={value} dense button className={classes.listItem}>
              <img src={teamImage(value)} className={classes.img} />
              <ListItemText primary={` ${value}`} />
            </ListItem>
          ))}
        </List>
      </div>
    );
  }
}

GridPlayerTeamsMembership.propTypes = {
classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(GridPlayerTeamsMembership);