javascript - React 组件的 if/else 条件渲染不起作用
问题描述
import React, { Component } from 'react';
import axios from 'axios';
import { Button, Card } from 'semantic-ui-react';
class Games extends Component {
state = { games:[], showGames: false }
componentDidMount() {
axios.get('/api/board_games')
.then(res => {
this.setState({games: res.data});
})
}
toggleGames = () => {
this.setState({ showGames: !this.state.showGames })
}
gamesList = () => {
const {games} = this.state
return games.map( game =>
<Card key={game.id}>
<Card.Content>
<Card.Header>{game.title}</Card.Header>
<Card.Description>Players: {game.min_players} - {game.max_players}</Card.Description>
<Card.Description>Company: {game.company}</Card.Description>
<Card.Description>Time Needed: {game.time_needed}</Card.Description>
</Card.Content>
<Card.Content extra>
<Button basic color='green'>
Add to Library
</Button>
</Card.Content>
</Card>
)
}
render() {
const showGames = this.state
return (
<div>
<h1>Games</h1>
<h3>Your Games</h3>
{ showGames ? (
<div>
<Card.Group itemsPerRow={4}>{this.gamesList()}</Card.Group>
</div>
)
: (
<button onClick={this.toggleGames()}>Add a Game</button>
)
}
</div>
)
}
}
export default Games;
在我看来,渲染返回应该检查 showGames 是真还是假。在开始的状态下默认为false。出于这个原因,它应该呈现“添加游戏”按钮。但是,如果您单击该按钮,它应该将 showGames 切换为 true 并渲染游戏卡。相反,当我到达页面时,它会自动呈现卡片。我还想在 if/else 的第一部分添加完成添加,但是当我这样做时,我得到“超出最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。React 限制了嵌套更新以防止无限循环。”
解决方案
您设置 onClick 事件的方式导致它不断被调用。你应该像这样格式化它:
onClick={this.toggleGames}
或像这样:
onClick={() => this.toggleGames()}
推荐阅读
- python - RabbitMQ/Celery (eventlet):服务器意外关闭连接
- matplotlib - Matplotlib 绘图标签重叠
- android - 不可转换的类型;无法将“android.content.Context”转换为“com.example.xxxxx.PendingListFragment”
- youtube - 如何从 VidIQ 和 TubeBuddy 复制批量片尾复制功能?
- if-statement - 在电子表格单元格中使用带有多个 ELSEIF 和 ELSE 的 IF
- date - 保存到 Kafka 后日期转换为默认值
- windows - 如何在 Python/Go/C/Batch 中获取 Windows 中的扩展文件属性?
- swift - 当蓝牙设备在 CoreBluetooth 上连接或断开连接时执行操作
- java - Hibernate 4.3 在尝试映射三结构时加载数据库的所有元素时在 setter 内部发生异常
- python - 如何使用 numpy 计算数组一部分的平均值