简体   繁体   中英

Moving elements onclick from one array to another. Content in new array objects empty / not copied?

Good evening,

as a learning project I want to build a simple "Learning Cards" App. The structure is quite simple: you have cards with questions. After a button click, you can show the correct solution. You can also click on "Question solved" to move the learning card to the absolved cards.

I am struggling to realize the "moving the learning card to the absolved" cards part. I have a "questions" array. After "onSolvedClick" the solved card gets copied to the "solved" array which is set as the new solved state.

When I click on the "Frage gelöst" (question solved) button, a new card appears in the solved questions region. The problem is: the new card is empty (without the question / answer). It would be great if someone could help me at this point! I already spent hours on this problem today.

I guess my mistake is within the App.Js code, probably in "onSolvedKlick" or "solveFragen".

Thanks a lot!

App.Js:

import React, {Component} from 'react';
import CardList from './CardList.js';
import { fragen } from './fragen';
import SearchBox from './SearchBox';


class App extends Component { // As Class to access objects

    constructor () {
        super();
        this.state = {  // State needed to change state
            fragen: fragen,
            solved : [] ,
            searchfield: ''
        }
    }

    onSearchChange = (event) => {

        this.setState({searchfield: event.target.value});

    }

    onSolvedKlick = (id) => {
        console.log("Klick on solved"+id);
        var frage = this.state.fragen.filter(function(e) // Bei Klick auf Solved: filtere aus Ursprungsarray das Element mit gelöster iD
        {
            return e.id === id;
        });

        console.log(frage);
        const newSolvedArray = this.state.solved.slice();
        newSolvedArray.push(frage);
        this.setState({solved: newSolvedArray});

    }



    render(){ // DOM rendering
        const filteredFragen = this.state.fragen.filter(fragen =>{
            return fragen.frage.toLowerCase().includes(this.state.searchfield.toLowerCase());
        })

        const solveFragen = this.state.solved; 



        return(
            <div className='tc'>

                    <h1>Learning Cards</h1>
                    <SearchBox searchChange={this.onSearchChange}/>
                    <h2>Cards: To be learned!</h2>
                    <div>
                    <CardList fragen={filteredFragen} onSolvedKlick={this.onSolvedKlick}/>
                    <CardList fragen={solveFragen} onSolvedKlick={this.onSolvedKlick}/>
                    </div>




            </div>

        )

    }



}

export default App;

CardList.js:

import React from 'react';
import Card from './Card';

const CardList = ({fragen, onSolvedKlick}) => {
    const cardComponent = fragen.map( (user, i) => {
        return(<Card key={i} id={fragen[i].id} frage = {fragen[i].frage} antwort = { fragen[i].antwort} onSolvedKlick = {onSolvedKlick}/>);
            }
        )


    return (
        <div>
            {cardComponent}

        </div>


        );



}

export default CardList;

Card.js:

import React, {Component} from 'react';
import 'tachyons';



class Card extends Component {
  constructor(props) {
    super(props);
    this.state = {
        frage : props.frage,
        showAnswer : false
    };
  }



  _showAnswer = () => {
    const before = this.state.showAnswer;
    const after = !before; 
    this.setState({
      showAnswer: after
    });
  }



  render() {


    return (
        <div className ="fl w-50 w-25-m w-20-l pa2 bg-light-red ma3"> 
            <div>
                <h2>{this.props.frage}</h2>
                 { this.state.showAnswer && (<div>{this.props.antwort}</div>) }
                 <p></p>
                <input type="button" value="Antwort anzeigen"  className ="ma2"
                onClick={this._showAnswer.bind(null)}
                    />

                <input type="button" name="solved" value="Frage gelöst" className = "ma2 bg-light-green" 
                onClick={() =>this.props.onSolvedKlick(this.props.id)}
                    />

            </div>

        </div>
    );
  }
}

fragen.js (Questions):

export const fragen = [
  {
    id: 1,
    frage: 'What are trends in CPU design?',
    antwort: 'Multi-core processors, SIMD support, Combination of core private and shared caches Heterogeneity, Hardware support for energy control',
    topic: 'Cloud'
  },
   {
    id: 2,
    frage: 'What is typical for multi-core processors?',
    antwort: 'Cache Architecture (L1 private to core, L2 private to tile), Cache Coherence',
    topic: 'Cloud'
  },
   {
    id: 3,
    frage: 'What memory modes exist?',
    antwort: 'Flat mode, Cache Mode, Hybrid Mode',
    topic: 'Cloud'
  },
 {
    id: 4,
    frage: 'What memory modes exist?',
    antwort: 'Flat mode, Cache Mode, Hybrid Mode',
    topic: 'Cloud'
  },

];

Try this on your onSolvedKlick function:

    onSolvedKlick = (id) => {
        console.log("Klick on solved"+id);
        var frage = this.state.fragen.filter((e) => e.id === id);   
        this.setState({solved: [...this.state.solved, frage]});
    }

Try to avoid so many empty lines. Also keep your code always in english so it's easier for others to understand. I had the luck to be german too :)

Assuming that you want to move the questions from fragen array to solved array, here is how to do that.

onSolvedKlick = id => {
    console.log("Klick on solved" + id);
    var elementPos = this.state.fragen.map(function(x) {return x.id; }).indexOf(id); // Find the position of the selected item in the fragen 
    const currentItem = this.state.fragen.splice(elementPos,1)
    const newSolvedArray = this.state.solved;
    newSolvedArray.push(currentItem[0]);//splice gives an array
    this.setState({ solved: newSolvedArray }, function() {console.log(this.state)});
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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