简体   繁体   English

反应组件没有条件渲染?

[英]React components not conditionally rendering?

I am trying to build a simple website that will display a random lyric after the user selects a musical artist.我正在尝试构建一个简单的网站,该网站将在用户选择音乐艺术家后显示随机歌词。 I am struggling with making components appear on react after the button is clicked.单击按钮后,我正在努力使组件出现在反应中。 It is likely that this is a really simple issue given I just started working with React yesterday and learned JS a few days ago.考虑到我昨天刚开始使用 React 并在几天前学习了 JS,这很可能是一个非常简单的问题。 My first screen renders with the two artists and a button to chose between them, but I can't get anything past that to pop up.我的第一个屏幕呈现了两位艺术家和一个可供选择的按钮,但我无法弹出任何内容。 I also seem to be having trouble with the states not updating.我似乎也遇到了状态不更新的问题。


import axios from 'axios';
import React, {Component} from 'react'
import taylorSwift from './taylorswift.jpg';
import kanyeWest from './kanyewest.jpeg';

const TAYLOR_ID = "259675";
const KANYE_ID = "33091467";



class Game extends Component {
    constructor(props) {
        super(props);
        this.state = {
            artist_id: "",
            lyric: "", 
            actualTrack: "", 
            userTrack: "",
            artistSelected: false
        };
      }


    async getRandomLyric(artist_id) {
       const response = await axios.get(`http://localhost:3000/randomlyric/:${artist_id}`);
       this.setState({
        lyric :response.lyric, 
        actualTrack: response.actualTrack});
    }

    choseArtist(artist_id) {
         this.setState({
            artist_id: artist_id,
            artistSelected: true
        })

        return (
            <div>
            <p> Great! Now you a random lyric from the artist you chose will be presented and</p>
            <p> you will have to guess which song this lyric is from. </p> 
            <p> Good luck! </p>

            <div>
                {this.getRandomLyric(artist_id)}
                <p>What track is this lyric from: {this.state.lyric} </p>
                <input type = "text" onChange ={ (e) => {
                this.setState({userTrack: e.target.value})
                }}/>
            </div>
    </div>
    )
    
    }

   showLyrics (artist_id) {
        
   }


    render() {
    return (

        <div>
            <h1>Welcome to the Song Guessing Game!</h1> 
            <p> These are the rules of the game: </p>
            <p> First, you must pick whether you are Team Taylor or Team Kanye.</p>
            <p> After you pick your team, you will be presented with 5 random lyrics from your chosen artist.</p>
            <p> Your job is to guess which song each lyric is from. </p>
            <p> Good luck!</p>

            
            <div className = "team_taylor">
                <div>
                    <img className = "artist_picture"
                    src={taylorSwift} 
                    alt="Taylor Swift" />
                </div>

                <div className = "artist_button">
                    <button onClick={()=>{this.choseArtist(TAYLOR_ID); this.forceUpdate()}}> Team Taylor</button>
                </div>
                
            </div>
            

            <div className = "team_kanye">
                <div>
                    <img className = "artist_picture"
                    src={kanyeWest} 
                    alt="Kanye West"/>
                </div>
            
            <div className = "artist_button">
                <button onClick={()=>{this.choseArtist(KANYE_ID); this.forceUpdate()}}> Team Kanye</button>
            </div>
        </div>

    


    
            
        
        


    </div>

    );
        }
}

export default Game;

If you just started learning react I recommend you to learn React functional components and React hooks .如果你刚开始学习 React,我建议你学习React 功能组件React 钩子

Here is an example of how your component would look like following the react functional components and hooks structure.这是一个示例,说明您的组件如何遵循反应功能组件和钩子结构。

import { useEffect, useState } from "react";

const Game = () => {
  const [artist, setArtist] = useState({
    artist_id: "",
    lyric: false,
    actualTrack: "",
    userTrack: "",
    artistSelected: false
  });

  useEffect(() => {
   artist.artistSelected &&  axios
      .get(`http://localhost:3000/randomlyric/:${artist_id}`)
      .then((response) =>
        setArtist((prev) => ({
          ...prev,
          lyric: response.lyric,
          actualTrack: response.actualTrack
        }))
      )
      .catch(error => console.log(error));
  }, [artist.artistSelected]);

  return artist.lyric ? (
    <div>
      <p>
        {" "}
        Great! Now you a random lyric from the artist you chose will be
        presented and
      </p>
      <p> you will have to guess which song this lyric is from. </p>
      <p> Good luck! </p>

      <div>
        <p>What track is this lyric from: {artist.lyric} </p>
        <input
          type="text"
          onChange={(e) => {
            setArtist(prev => ({...prev, userTrack:e.target.value}))
          }}
        />
      </div>
    </div>
  ) : (
    <div>
      <h1>Welcome to the Song Guessing Game!</h1>
      <p> These are the rules of the game: </p>
      <p> First, you must pick whether you are Team Taylor or Team Kanye.</p>
      <p>
        {" "}
        After you pick your team, you will be presented with 5 random lyrics
        from your chosen artist.
      </p>
      <p> Your job is to guess which song each lyric is from. </p>
      <p> Good luck!</p>

      <div className="team_taylor">
        <div>
          <img
            className="artist_picture"
            src={taylorSwift}
            alt="Taylor Swift"
          />
        </div>

        <div className="artist_button">
          <button
            onClick={() =>
              setArtist((prev) => ({
                ...prev,
                artist_id: TAYLOR_ID,
                artistSelected: true
              }))
            }
          >
            {" "}
            Team Taylor
          </button>
        </div>
      </div>

      <div className="team_kanye">
        <div>
          <img className="artist_picture" src={kanyeWest} alt="Kanye West" />
        </div>

        <div className="artist_button">
          <button
            onClick={() =>
              setArtist((prev) => ({
                ...prev,
                artist_id: KANYE_ID,
                artistSelected: true
              }))
            }
          >
            {" "}
            Team Kanye
          </button>
        </div>
      </div>
    </div>
  );
};

export default Game;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM