首页 > 解决方案 > 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 限制了嵌套更新以防止无限循环。”

标签: javascriptreactjs

解决方案


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

onClick={this.toggleGames}

或像这样:

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

推荐阅读