我正在尝试访问数组的不同索引以在我的一个组件中显示,但我遇到了问题。这是我目前使用的代码:
const mapStateToProps = (state) => {
return {
weight: state.move[0].movementWeight,
name: state.move[0].movementName
}
};
这是用户点击的按钮的代码,它决定了需要什么索引:
const MovementButton = (props) => {
const classes = useStyles();
const mapNames = props.name.map((lift) => {
return (
<Button
key={lift.movementName}
className={classes.movementButtons}
onClick={() => history.push(`/movement/${lift.movementName}/${lift.movementWeight}`)}
>
{lift.movementName} - {lift.movementWeight}lbs
</Button>
)
});
const displayMovementButtons = () => {
if (mapNames.length === 0) {
return <div className={classes.noMovementsMessage} >Click add button to begin</div>
};
return <div>{mapNames}</div>
};
return <div className={classes.movementButtonsDiv}>{displayMovementButtons()}</div>
};
const mapStateToProps = (state) => {
return {
name: state.move
}
};
export default connect(mapStateToProps)(MovementButton);
但这使得 props.weight 始终是 0 索引,而有时我需要索引 1、2 等。我使用 [0] 的原因是因为没有它,我会变得未定义。 有什么帮助吗?