【问题标题】:If/else conditional rendering of React components not workingReact 组件的 if/else 条件渲染不起作用
【发布时间】: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


【解决方案1】:

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

onClick={this.toggleGames}

或者像这样:

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

【讨论】:

    【解决方案2】:

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

    // the onClick is executing in every render.
    <button onClick={this.toggleGames()}>Add a Game</button>
    
    // right way
    button onClick={() => this.toggleGames()}>Add a Game</button>
    

    【讨论】:

      【解决方案3】:

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

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

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

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 2018-09-21
        • 1970-01-01
        • 2020-05-22
        • 1970-01-01
        • 2018-10-16
        • 2020-11-15
        • 1970-01-01
        • 1970-01-01
        • 2022-09-27
        相关资源
        最近更新 更多