簡體   English   中英

如果/其他條件渲染的React組件不起作用

[英]If/else conditional rendering of React components not working

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”的第一部分中添加“完成添加”,但是當我這樣做時,我得到“超出最大更新深度。當組件在componentWillUpdate或componentDidUpdate中重復調用setState時,可能會發生這種情況。React限制了嵌套更新以防止無限循環。”

您設置onClick事件的方式導致它被不斷調用。 您應該像這樣格式化它:

onClick={this.toggleGames}

或像這樣:

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

您從按鈕設置了錯誤的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>

只需在render()編輯以下行:

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

目前,您的showGames常量是一個對象,而不是布爾值。 因此,您將無法有條件地使用它。

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM