Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

javascript - props state values in reactjs

I am a beginner in ReactJS trying to make a quiz app. In the game form user has to input country names and will get a point for every correct answer.The final score will be shown in Result form but cant get the state score value to Result.js form . The props command is the handleSubmit function ,using 'points' as an attribute

Game form js

import React, { Component } from 'react'
import './game.css'
import axios from 'axios'
import Result from '../Result/Result'
class game extends Component{
    constructor(props){
        super(props);

        this.state={
            dataIsLoaded : false,
            answer:'',
            countries:[],
            index:0,
            links : [],
            submitimes:1,
            countriesnames:[],
            score:0,
            temp:0
        }
        this.handleChange=this.handleChange.bind(this);
        this.handleSubmit=this.handleSubmit.bind(this);
        this.handleSkip=this.handleSkip.bind(this);
        this.handleHint=this.handleHint.bind(this);
    }

    componentDidMount(){
        if(this.state.dataIsLoaded===false)
        this.fetchData();
    }

    fetchData = async () => {
        await axios.get('https://peaceful-temple-16111.herokuapp.com/https://salty-cove-08526.herokuapp.com/api/countries?format=json')
            .then(res => {
                console.log("fetched data")
                this.setState({ countries: res.data });
                let links = []
                this.state.countries.map(country =>
                    links.push(country.photo)
                )
                let countriesnames=[]
                this.state.countries.map(country=>
                    countriesnames.push(country.name)
                )
                console.log(countriesnames)
                this.setState({
                    links,
                    countriesnames,
                    dataIsLoaded: true,
                    answer:''
                })
            })
    }

    handleSubmit=(e)=>{
        
        e.preventDefault();  

            if(this.state.answer==""){
                alert("Please enter Country Name before Submitting")
            }else{
                if(this.state.countriesnames[this.state.index].toLowerCase()==this.state.answer.toLowerCase()){
                    this.setState({
                        score:this.state.score + 1
                    })
                    if(this.state.submitimes==3){
                        this.setState({
                            temp:this.state.temp+1
                        })
                    }
              
              
                    console.log("score=",this.state.score)
                }else{
                    console.log("score=",this.state.score)
                 
                }
                console.log("userinput=",this.state.answer)

                this.setState({
                    index: this.state.index + 1,
                    submitimes:this.state.submitimes+1,
                    answer:""
                })
                console.log('index=',this.state.index)
                console.log('times=',this.state.submitimes)
            
               
            }
            
    
            <Result points={this.state.score}/> /////<=here
            window.location="/result"
        }
    }

Result form js

import React,{Component} from 'react'
import './Result.css'
import Game from '../game/game'

class Result extends Component{
    constructor(props){
        super(props);
        this.state={
        }
    }
    render(){
        return(
            <div>
                <section className="result">
                    <div className="lContainer">
                        <div class="rheading">
                            Congratulation's your Score was:
                        </div >
                        <div className="points">{this.props.points}</div> /////<=here
                    </div>
                </section>
            </div>
        );
    }
}

export default Result;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You must note that React is a Single Page application. And to introduce Routes in your Application you will need a third party library, react-router-dom is one of those libraries.

So, doing window.location="/result" doesn't mean anything here. In Single Page application, we don't have a seperate HTML page called results.html. It's just one huge SPA (index.html) and everything goes with our root div in our index.html in the public folder.

<div id="root"></div>

I will not go with each and every detail about react-router-dom . Go through this documentation to get started.

https://reactrouter.com/web/guides/quick-start

UPDATE: From comment, It seems you also wants to know about passing the score to Child Component.

To link b/w different components in your app, you should go with react-router-dom as mentioned above.

CASE B: In order to pass the score to the Result component, you do not need to use <Result points={this.state.score} /> nor window.location in your handleSubmit() method. The way you have done this will result in error in your app.

You simply need to use your Result component within Game component inside the render() function within return().

Game.js Should look like below code. So that Result Component gets rendered within Game Component.

import React, { Component } from "react";
import Result from "./Result";

class Game extends Component {
  constructor(props) {
    super(props);

    this.state = {
      score: 34
    };
  }

  render() {
    return (
      <div>
        <Result points={this.state.score} />
      </div>
    );
  }
}

export default Game;

a) Also I checked that you have imported Game Component in Result Component. That is not needed at all. This will ultimately mean You will render a parent component Game in the child component Result.

FULL CODE DEMO OF HOW BOTH YOU YOUR COMPONENTS SHOULD LOOK LIKE :

const {Component} = React;

class Game extends Component {
  constructor(props) {
    super(props);

    this.state = {
      score: 34
    };
  }

  render() {
    return (
      <div>
        <Result points={this.state.score} />
      </div>
    );
  }
}

class Result extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return (
      <div>
        <section className="result">
          <div className="lContainer">
            <div class="rheading">Congratulation's your Score was:</div>
            <div className="points">{this.props.points}       </div>
          </div>
        </section>
      </div>
    );
  }
}

ReactDOM.render(<Game/>, document.getElementById("root"));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...