javascript - React&Redux:我在后台有状态,但无法在我的 JSX 中呈现循环数组
问题描述
到目前为止,我已经GET_TOURNAMENTS
将所有锦标赛对象设置为我的状态,并在页面上呈现它们。
然后,我给每个锦标赛一个调用按钮,该按钮showTournament()
选择我点击的任何锦标赛,并更新状态。当我点击SHOW_TOURNAMENT
我的状态看起来像:
tournament
tournaments: [{...}, {...}] <<~~this is from GET_TOURNAMENTS
showTournament: { <<~~begins as (showTournament: "") until showTournament() action
_id: "etc",
title: "Tournament One",
status: "Open",
participants: [ <<~~an array of User objects
0: {_id: "asdf", username: "asdf"},
1: {_id: "asdf", username: "asdf"}
]
}
Annnnnnnnd 我试图通过执行以下操作在我的 ShowTournament 组件中呈现所有这些:
class TournamentShow extends Component {
static propTypes = {
tournament: PropTypes.object.isRequired,
auth: PropTypes.object.isRequired
};
render() {
const { _id, title, hostedBy, status, participants } = this.props.tournament.showTournament;
return (
<div>
<h1>{ title }</h1>
<p>status: { status }</p>
<p>Registered Participants:</p>
{
participants ?
participants.forEach(participant => {
return (
<ul>
<li>{participant}</li>
</ul>
)
}) :
null
}
<p>Hosted by: { hostedBy }</p>
<Link to="#">Sign Up</Link><br/>
<Link to="/">Back to Tournaments main page</Link>
</div>
)
}
};
const mapStateToProps = state => ({
tournament: state.tournament,
auth: state.auth
});
export default connect(mapStateToProps, { showTournament })(TournamentShow);
这说明什么。即使数组中有参与者,也不会呈现任何内容。
我也尝试过简单 <<~~ 编辑:我一开始有标签,把它们放在 {} 之外
<p>Registered Participants:</p>
<ul>
{
participants.forEach(participant => {
return (
<li>{participant}</li>
)
})
}
</ul>
我得到错误TypeError: Cannot read property 'forEach' of undefined
渲染中的所有非数组数据showTournament
都很好。我发现了其他 Stack Overflow 问题并尝试了许多解决方案,但其他问题完全不同,以至于我无法弄清楚如何获得正确的实现。
谢谢大家!
解决方案
1)你需要使用map
,因为forEach
不返回任何东西,所以你返回的任何东西forEach
对外部世界都是不可见的forEach
。map将返回一个数组。
2)你想做什么{participant}
?它是一个对象,所以要么使用打印它,要么JSON.stringify(participant)
更好,打印_id
并username
单独打印,如下所示:
participants.map(participant =>
(
<ul>
<li>{participant._id}</li>
<li>{participant.username}</li>
</ul>
)
)
3)如果您如您所说遇到错误,那么很可能participants
是undefined
. 您可以尝试调试并查看其值是否已填充。如果无法调试,只需尝试使用打印它
<div>{JSON.stringify(participants)}</div>
甚至
<div>{JSON.stringify(this.props.tournament.showTournament)}</div>
推荐阅读
- javascript - 如何在侧边栏打开整个屏幕半黑?
- angular - 将通过 Nginx 发出的请求直接发送到 Angular 路由组件
- javascript - 通过相同的类名更改所有 ID 值
- c# - ASP.net webforms 存储过程中的异步调用
- jsf-2 - 当我将默认语言环境定义为 es_ES 时,为什么会出现 MissingResourceException 语言环境 en_US?
- c# - 如何使用数组计算总数和最小生成树
- java - 为什么 Integer.MAX_VALUE*2 返回 -2?
- javascript - 我想在父 div 中附加最后一个克隆的 div
- javascript - 在 JavaScript 中全局区分大小写的 RegExp 中仅获取一个字符不区分大小写
- java - 带有java codejersey的jsp