如果/其他条件渲染的React组件不起作用

时间:2018-11-30 20:49:43

标签: javascript reactjs

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是true还是false。一开始的状态默认为false。因此,它应呈现“添加游戏”按钮。但是,如果您单击该按钮,它将把showGames切换为true并渲染游戏卡。相反,当我到达页面时,它将自动呈现卡片。我还想在“ if / else”的第一部分中添加“ Done Adding”,但是当我这样做时,我得到“超出最大更新深度。当组件在componentWillUpdate或componentDidUpdate中重复调用setState时,可能会发生这种情况。React限制了嵌套更新以防止无限循环。”

3 个答案:

答案 0 :(得分:1)

您设置onClick事件的方式导致它被不断调用。您应该这样格式化它:

onClick={this.toggleGames}

或类似这样:

onClick={() => this.toggleGames()}

答案 1 :(得分:0)

您通过按钮设置了错误的onClick操作

mapgeo := &MapGeometry{}
db.Create(mapgeo)

答案 2 :(得分:0)

只需在render()中编辑以下行:

const showGames = this.state.showGames;
or
const { showGames } = this.state;

目前,您的showGames常量是一个对象,而不是布尔值。因此,您将无法有条件地使用它。

希望这会有所帮助!

相关问题