【发布时间】:2019-05-03 00:48:00
【问题描述】:
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 限制了嵌套更新以防止无限循环。”
【问题讨论】:
-
const { showGames } = this.state
标签: javascript reactjs