React-Native Imported Component not initializing its state on Parent state change












0














I am creating a Memory Card game on React-Native, I am using this repository for Flip Animation https://github.com/lhandel/react-native-card-flip.



On level 1 when I match all cards then I am setting state to change level and on Level 2 cards are still flipped, I want then to be on their initial state.



Level 1 before solving:
Level 1 Image



Level 2 after solving Level 1:
Level 2 Image



What I want is on level 2, it should render imported CardFlip component drawing cards back face like it do initially (like in Level 1).



I am using react-native, not expo. Put this my code in App.js file and import card-flip repository and run-android this code with react-native.






import React, { Component } from 'react';
import {
StyleSheet,
Image,
View, Dimensions, Text,
TouchableOpacity
} from 'react-native';

import CardFlip from 'react-native-card-flip';

export default class App extends Component<Props> {

constructor(props){
super(props)
this.state = {
page: true,
level: 1,
tries: 0,
}
this.width = Dimensions.get('window').width;
this.levels = {
1:{cards:4,rowItems:2,tries:3,card_width:(this.width/2)-15},
2:{cards:6,rowItems:2,tries:5,card_width:(this.width/2)-15},
3:{cards:8,rowItems:2,tries:6,card_width:(this.width/2)-70},
4:{cards:12,rowItems:3,tries:8,card_width:(this.width/3)-50},
5:{cards:14,rowItems:3,tries:9,card_width:(this.width/3)-50},
6:{cards:18,rowItems:3,tries:12,card_width:(this.width/3)-50},
7:{cards:24,rowItems:4,tries:16,card_width:(this.width/4)-15},
8:{cards:30,rowItems:5,tries:20,card_width:(this.width/5)-15},
9:{cards:34,rowItems:5,tries:22,card_width:(this.width/5)-15},
10:{cards:40,rowItems:5,tries:25,card_width:(this.width/5)-15}
};
this.dimens = {width: this.levels[this.state.level].card_width, height: this.levels[this.state.level].card_width};
}

go_next = () =>{
this.setState({page: false, tries:0, level: 1});
};
go_home = () =>{
this.setState({page: true});
};

tried = ()=>{
this.setState({tries: this.state.tries+1});
};
level_up = ()=>{
console.log("level up: ", this.state.level+1);
this.setState({level: this.state.level+1, tries: 0});
};
level_restart = ()=>{
console.log("level restarted: ", this.state.level);
this.setState({level: this.state.level, tries: 0});
}

render() {
if (this.state.page) {
return (
<View style={styles.container}>
<Text style={styles.heading}>Cardy</Text>
<Text>Color Memory Game for Kids</Text>
<TouchableOpacity onPress={this.go_next}>
<Image style={{marginBottom:30}} source={require("./assets/play.png")}></Image>
</TouchableOpacity>
</View>
);
} else {
return (
<View style={{flex:1}}>
<View style={{flex:.1,alignItems: 'center',justifyContent:'flex-end',marginTop:20}}><Text style={styles.subheading}>Level {this.state.level}</Text><Text>Tries Remaining: {(this.levels[this.state.level].tries-this.state.tries)}</Text></View>

<Cards dimens={this.dimens} cards={this.levels[this.state.level].cards} rowItems={this.levels[this.state.level].rowItems} tried={this.tried.bind(this)} level_up={this.level_up.bind(this)} level_restart={this.level_restart.bind(this)} level={this.state.level} tries={this.state.tries} total_tries={this.levels[this.state.level].tries} />

<View style={{alignItems: 'center',flex:.1}}>
<TouchableOpacity onPress={this.go_home}>
<Text>← Go Home</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
}

class Cards extends Component<props> {
constructor(props){
super(props)
this.color='';
this.ckey='';
this.tries=0;
this.matched=0;
this.level = this.props.level;
}

shouldComponentUpdate(nextProps, nextState){
if( this.level != nextProps.level || nextProps.tries==0 )
return true;
else return false;
}

do_flip = (color, ckey)=>{
if( this.color != '' ){ // second card flip
this.props.tried();
this.tries++;
if( this.color == color ){ //card matched
this.matched++;
this["card"+ckey].flip();
if( this.matched == this.props.cards/2 ){
this.tries=0;
this.matched=0;
alert("Level completed successfully.");
this.props.level_up();
}
else if( this.tries == this.props.total_tries ){
alert("Sorry, Level failed, try again.");
this.tries=0;
this.matched=0;
this.props.level_restart();
}
} else { // card not matched
var pkey = this.ckey;
this["card"+pkey].flip();
if( this.tries == this.props.total_tries ){
this.tries=0;
this.matched=0;
alert("Sorry, Level failed, try again.");
this.props.level_restart();
}
}
this.color='';
this.ckey='';
} else { // first card flip
this["card"+ckey].flip();
this.color=color;
this.ckey=ckey;
}
};

shuffleArray = (array) => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}

generate_cards = ()=>{
const inner_cards = this.props.rowItems;
const main_loops = Math.ceil(this.props.cards/inner_cards);
const colors = ["blue","green","red","yellow","black","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","blanchedalmond","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","yellowgreen"];
var selected_colors = colors.slice(0, this.props.cards/2);
selected_colors = selected_colors.concat(selected_colors);
this.shuffleArray(selected_colors);
var cd = 0;
let row = ;
let card = ;
var list = selected_colors.map( (color, key)=> {
if( cd == 0 ) { card = ; }
card.push(
<CardFlip style={this.props.dimens} key={key} ref={(card) => this["card"+key] = card}>
<TouchableOpacity activeOpacity={1} style={this.props.dimens} onPress={() => {this.do_flip(color,key); }} >
<Image style={this.props.dimens} source={require("./assets/robot.png")}></Image>
</TouchableOpacity>
<TouchableOpacity activeOpacity={0} style={[this.props.dimens]}>
<View style={[{backgroundColor:color}, this.props.dimens]}></View>
</TouchableOpacity>
</CardFlip>
);
cd++;
if( cd==inner_cards || key == selected_colors.length-1 ){
cd=0;
return <View key={key+"a"} style={{flex:1,flexDirection:'row',justifyContent:'space-evenly',alignItems: 'center'}}>{card}</View>
}
});
return list;
}
render(){
return (
<View style={{flex:.8}}>
{this.generate_cards()}
</View>
)
}
}

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
heading:{
fontSize: 40,
color: 'green',
fontWeight:'bold',
marginBottom: 20
},
subheading:{
fontSize: 30,
color: 'green',
fontWeight:'bold',
marginBottom: 20
},
boxContainer: {
flex: 1,
alignItems: 'center',
flexDirection: 'column',
backgroundColor:'yellow'
}
});












share|improve this question



























    0














    I am creating a Memory Card game on React-Native, I am using this repository for Flip Animation https://github.com/lhandel/react-native-card-flip.



    On level 1 when I match all cards then I am setting state to change level and on Level 2 cards are still flipped, I want then to be on their initial state.



    Level 1 before solving:
    Level 1 Image



    Level 2 after solving Level 1:
    Level 2 Image



    What I want is on level 2, it should render imported CardFlip component drawing cards back face like it do initially (like in Level 1).



    I am using react-native, not expo. Put this my code in App.js file and import card-flip repository and run-android this code with react-native.






    import React, { Component } from 'react';
    import {
    StyleSheet,
    Image,
    View, Dimensions, Text,
    TouchableOpacity
    } from 'react-native';

    import CardFlip from 'react-native-card-flip';

    export default class App extends Component<Props> {

    constructor(props){
    super(props)
    this.state = {
    page: true,
    level: 1,
    tries: 0,
    }
    this.width = Dimensions.get('window').width;
    this.levels = {
    1:{cards:4,rowItems:2,tries:3,card_width:(this.width/2)-15},
    2:{cards:6,rowItems:2,tries:5,card_width:(this.width/2)-15},
    3:{cards:8,rowItems:2,tries:6,card_width:(this.width/2)-70},
    4:{cards:12,rowItems:3,tries:8,card_width:(this.width/3)-50},
    5:{cards:14,rowItems:3,tries:9,card_width:(this.width/3)-50},
    6:{cards:18,rowItems:3,tries:12,card_width:(this.width/3)-50},
    7:{cards:24,rowItems:4,tries:16,card_width:(this.width/4)-15},
    8:{cards:30,rowItems:5,tries:20,card_width:(this.width/5)-15},
    9:{cards:34,rowItems:5,tries:22,card_width:(this.width/5)-15},
    10:{cards:40,rowItems:5,tries:25,card_width:(this.width/5)-15}
    };
    this.dimens = {width: this.levels[this.state.level].card_width, height: this.levels[this.state.level].card_width};
    }

    go_next = () =>{
    this.setState({page: false, tries:0, level: 1});
    };
    go_home = () =>{
    this.setState({page: true});
    };

    tried = ()=>{
    this.setState({tries: this.state.tries+1});
    };
    level_up = ()=>{
    console.log("level up: ", this.state.level+1);
    this.setState({level: this.state.level+1, tries: 0});
    };
    level_restart = ()=>{
    console.log("level restarted: ", this.state.level);
    this.setState({level: this.state.level, tries: 0});
    }

    render() {
    if (this.state.page) {
    return (
    <View style={styles.container}>
    <Text style={styles.heading}>Cardy</Text>
    <Text>Color Memory Game for Kids</Text>
    <TouchableOpacity onPress={this.go_next}>
    <Image style={{marginBottom:30}} source={require("./assets/play.png")}></Image>
    </TouchableOpacity>
    </View>
    );
    } else {
    return (
    <View style={{flex:1}}>
    <View style={{flex:.1,alignItems: 'center',justifyContent:'flex-end',marginTop:20}}><Text style={styles.subheading}>Level {this.state.level}</Text><Text>Tries Remaining: {(this.levels[this.state.level].tries-this.state.tries)}</Text></View>

    <Cards dimens={this.dimens} cards={this.levels[this.state.level].cards} rowItems={this.levels[this.state.level].rowItems} tried={this.tried.bind(this)} level_up={this.level_up.bind(this)} level_restart={this.level_restart.bind(this)} level={this.state.level} tries={this.state.tries} total_tries={this.levels[this.state.level].tries} />

    <View style={{alignItems: 'center',flex:.1}}>
    <TouchableOpacity onPress={this.go_home}>
    <Text>← Go Home</Text>
    </TouchableOpacity>
    </View>
    </View>
    );
    }
    }
    }

    class Cards extends Component<props> {
    constructor(props){
    super(props)
    this.color='';
    this.ckey='';
    this.tries=0;
    this.matched=0;
    this.level = this.props.level;
    }

    shouldComponentUpdate(nextProps, nextState){
    if( this.level != nextProps.level || nextProps.tries==0 )
    return true;
    else return false;
    }

    do_flip = (color, ckey)=>{
    if( this.color != '' ){ // second card flip
    this.props.tried();
    this.tries++;
    if( this.color == color ){ //card matched
    this.matched++;
    this["card"+ckey].flip();
    if( this.matched == this.props.cards/2 ){
    this.tries=0;
    this.matched=0;
    alert("Level completed successfully.");
    this.props.level_up();
    }
    else if( this.tries == this.props.total_tries ){
    alert("Sorry, Level failed, try again.");
    this.tries=0;
    this.matched=0;
    this.props.level_restart();
    }
    } else { // card not matched
    var pkey = this.ckey;
    this["card"+pkey].flip();
    if( this.tries == this.props.total_tries ){
    this.tries=0;
    this.matched=0;
    alert("Sorry, Level failed, try again.");
    this.props.level_restart();
    }
    }
    this.color='';
    this.ckey='';
    } else { // first card flip
    this["card"+ckey].flip();
    this.color=color;
    this.ckey=ckey;
    }
    };

    shuffleArray = (array) => {
    for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
    }
    }

    generate_cards = ()=>{
    const inner_cards = this.props.rowItems;
    const main_loops = Math.ceil(this.props.cards/inner_cards);
    const colors = ["blue","green","red","yellow","black","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","blanchedalmond","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","yellowgreen"];
    var selected_colors = colors.slice(0, this.props.cards/2);
    selected_colors = selected_colors.concat(selected_colors);
    this.shuffleArray(selected_colors);
    var cd = 0;
    let row = ;
    let card = ;
    var list = selected_colors.map( (color, key)=> {
    if( cd == 0 ) { card = ; }
    card.push(
    <CardFlip style={this.props.dimens} key={key} ref={(card) => this["card"+key] = card}>
    <TouchableOpacity activeOpacity={1} style={this.props.dimens} onPress={() => {this.do_flip(color,key); }} >
    <Image style={this.props.dimens} source={require("./assets/robot.png")}></Image>
    </TouchableOpacity>
    <TouchableOpacity activeOpacity={0} style={[this.props.dimens]}>
    <View style={[{backgroundColor:color}, this.props.dimens]}></View>
    </TouchableOpacity>
    </CardFlip>
    );
    cd++;
    if( cd==inner_cards || key == selected_colors.length-1 ){
    cd=0;
    return <View key={key+"a"} style={{flex:1,flexDirection:'row',justifyContent:'space-evenly',alignItems: 'center'}}>{card}</View>
    }
    });
    return list;
    }
    render(){
    return (
    <View style={{flex:.8}}>
    {this.generate_cards()}
    </View>
    )
    }
    }

    const styles = StyleSheet.create({
    container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
    },
    heading:{
    fontSize: 40,
    color: 'green',
    fontWeight:'bold',
    marginBottom: 20
    },
    subheading:{
    fontSize: 30,
    color: 'green',
    fontWeight:'bold',
    marginBottom: 20
    },
    boxContainer: {
    flex: 1,
    alignItems: 'center',
    flexDirection: 'column',
    backgroundColor:'yellow'
    }
    });












    share|improve this question

























      0












      0








      0







      I am creating a Memory Card game on React-Native, I am using this repository for Flip Animation https://github.com/lhandel/react-native-card-flip.



      On level 1 when I match all cards then I am setting state to change level and on Level 2 cards are still flipped, I want then to be on their initial state.



      Level 1 before solving:
      Level 1 Image



      Level 2 after solving Level 1:
      Level 2 Image



      What I want is on level 2, it should render imported CardFlip component drawing cards back face like it do initially (like in Level 1).



      I am using react-native, not expo. Put this my code in App.js file and import card-flip repository and run-android this code with react-native.






      import React, { Component } from 'react';
      import {
      StyleSheet,
      Image,
      View, Dimensions, Text,
      TouchableOpacity
      } from 'react-native';

      import CardFlip from 'react-native-card-flip';

      export default class App extends Component<Props> {

      constructor(props){
      super(props)
      this.state = {
      page: true,
      level: 1,
      tries: 0,
      }
      this.width = Dimensions.get('window').width;
      this.levels = {
      1:{cards:4,rowItems:2,tries:3,card_width:(this.width/2)-15},
      2:{cards:6,rowItems:2,tries:5,card_width:(this.width/2)-15},
      3:{cards:8,rowItems:2,tries:6,card_width:(this.width/2)-70},
      4:{cards:12,rowItems:3,tries:8,card_width:(this.width/3)-50},
      5:{cards:14,rowItems:3,tries:9,card_width:(this.width/3)-50},
      6:{cards:18,rowItems:3,tries:12,card_width:(this.width/3)-50},
      7:{cards:24,rowItems:4,tries:16,card_width:(this.width/4)-15},
      8:{cards:30,rowItems:5,tries:20,card_width:(this.width/5)-15},
      9:{cards:34,rowItems:5,tries:22,card_width:(this.width/5)-15},
      10:{cards:40,rowItems:5,tries:25,card_width:(this.width/5)-15}
      };
      this.dimens = {width: this.levels[this.state.level].card_width, height: this.levels[this.state.level].card_width};
      }

      go_next = () =>{
      this.setState({page: false, tries:0, level: 1});
      };
      go_home = () =>{
      this.setState({page: true});
      };

      tried = ()=>{
      this.setState({tries: this.state.tries+1});
      };
      level_up = ()=>{
      console.log("level up: ", this.state.level+1);
      this.setState({level: this.state.level+1, tries: 0});
      };
      level_restart = ()=>{
      console.log("level restarted: ", this.state.level);
      this.setState({level: this.state.level, tries: 0});
      }

      render() {
      if (this.state.page) {
      return (
      <View style={styles.container}>
      <Text style={styles.heading}>Cardy</Text>
      <Text>Color Memory Game for Kids</Text>
      <TouchableOpacity onPress={this.go_next}>
      <Image style={{marginBottom:30}} source={require("./assets/play.png")}></Image>
      </TouchableOpacity>
      </View>
      );
      } else {
      return (
      <View style={{flex:1}}>
      <View style={{flex:.1,alignItems: 'center',justifyContent:'flex-end',marginTop:20}}><Text style={styles.subheading}>Level {this.state.level}</Text><Text>Tries Remaining: {(this.levels[this.state.level].tries-this.state.tries)}</Text></View>

      <Cards dimens={this.dimens} cards={this.levels[this.state.level].cards} rowItems={this.levels[this.state.level].rowItems} tried={this.tried.bind(this)} level_up={this.level_up.bind(this)} level_restart={this.level_restart.bind(this)} level={this.state.level} tries={this.state.tries} total_tries={this.levels[this.state.level].tries} />

      <View style={{alignItems: 'center',flex:.1}}>
      <TouchableOpacity onPress={this.go_home}>
      <Text>← Go Home</Text>
      </TouchableOpacity>
      </View>
      </View>
      );
      }
      }
      }

      class Cards extends Component<props> {
      constructor(props){
      super(props)
      this.color='';
      this.ckey='';
      this.tries=0;
      this.matched=0;
      this.level = this.props.level;
      }

      shouldComponentUpdate(nextProps, nextState){
      if( this.level != nextProps.level || nextProps.tries==0 )
      return true;
      else return false;
      }

      do_flip = (color, ckey)=>{
      if( this.color != '' ){ // second card flip
      this.props.tried();
      this.tries++;
      if( this.color == color ){ //card matched
      this.matched++;
      this["card"+ckey].flip();
      if( this.matched == this.props.cards/2 ){
      this.tries=0;
      this.matched=0;
      alert("Level completed successfully.");
      this.props.level_up();
      }
      else if( this.tries == this.props.total_tries ){
      alert("Sorry, Level failed, try again.");
      this.tries=0;
      this.matched=0;
      this.props.level_restart();
      }
      } else { // card not matched
      var pkey = this.ckey;
      this["card"+pkey].flip();
      if( this.tries == this.props.total_tries ){
      this.tries=0;
      this.matched=0;
      alert("Sorry, Level failed, try again.");
      this.props.level_restart();
      }
      }
      this.color='';
      this.ckey='';
      } else { // first card flip
      this["card"+ckey].flip();
      this.color=color;
      this.ckey=ckey;
      }
      };

      shuffleArray = (array) => {
      for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
      }
      }

      generate_cards = ()=>{
      const inner_cards = this.props.rowItems;
      const main_loops = Math.ceil(this.props.cards/inner_cards);
      const colors = ["blue","green","red","yellow","black","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","blanchedalmond","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","yellowgreen"];
      var selected_colors = colors.slice(0, this.props.cards/2);
      selected_colors = selected_colors.concat(selected_colors);
      this.shuffleArray(selected_colors);
      var cd = 0;
      let row = ;
      let card = ;
      var list = selected_colors.map( (color, key)=> {
      if( cd == 0 ) { card = ; }
      card.push(
      <CardFlip style={this.props.dimens} key={key} ref={(card) => this["card"+key] = card}>
      <TouchableOpacity activeOpacity={1} style={this.props.dimens} onPress={() => {this.do_flip(color,key); }} >
      <Image style={this.props.dimens} source={require("./assets/robot.png")}></Image>
      </TouchableOpacity>
      <TouchableOpacity activeOpacity={0} style={[this.props.dimens]}>
      <View style={[{backgroundColor:color}, this.props.dimens]}></View>
      </TouchableOpacity>
      </CardFlip>
      );
      cd++;
      if( cd==inner_cards || key == selected_colors.length-1 ){
      cd=0;
      return <View key={key+"a"} style={{flex:1,flexDirection:'row',justifyContent:'space-evenly',alignItems: 'center'}}>{card}</View>
      }
      });
      return list;
      }
      render(){
      return (
      <View style={{flex:.8}}>
      {this.generate_cards()}
      </View>
      )
      }
      }

      const styles = StyleSheet.create({
      container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
      },
      heading:{
      fontSize: 40,
      color: 'green',
      fontWeight:'bold',
      marginBottom: 20
      },
      subheading:{
      fontSize: 30,
      color: 'green',
      fontWeight:'bold',
      marginBottom: 20
      },
      boxContainer: {
      flex: 1,
      alignItems: 'center',
      flexDirection: 'column',
      backgroundColor:'yellow'
      }
      });












      share|improve this question













      I am creating a Memory Card game on React-Native, I am using this repository for Flip Animation https://github.com/lhandel/react-native-card-flip.



      On level 1 when I match all cards then I am setting state to change level and on Level 2 cards are still flipped, I want then to be on their initial state.



      Level 1 before solving:
      Level 1 Image



      Level 2 after solving Level 1:
      Level 2 Image



      What I want is on level 2, it should render imported CardFlip component drawing cards back face like it do initially (like in Level 1).



      I am using react-native, not expo. Put this my code in App.js file and import card-flip repository and run-android this code with react-native.






      import React, { Component } from 'react';
      import {
      StyleSheet,
      Image,
      View, Dimensions, Text,
      TouchableOpacity
      } from 'react-native';

      import CardFlip from 'react-native-card-flip';

      export default class App extends Component<Props> {

      constructor(props){
      super(props)
      this.state = {
      page: true,
      level: 1,
      tries: 0,
      }
      this.width = Dimensions.get('window').width;
      this.levels = {
      1:{cards:4,rowItems:2,tries:3,card_width:(this.width/2)-15},
      2:{cards:6,rowItems:2,tries:5,card_width:(this.width/2)-15},
      3:{cards:8,rowItems:2,tries:6,card_width:(this.width/2)-70},
      4:{cards:12,rowItems:3,tries:8,card_width:(this.width/3)-50},
      5:{cards:14,rowItems:3,tries:9,card_width:(this.width/3)-50},
      6:{cards:18,rowItems:3,tries:12,card_width:(this.width/3)-50},
      7:{cards:24,rowItems:4,tries:16,card_width:(this.width/4)-15},
      8:{cards:30,rowItems:5,tries:20,card_width:(this.width/5)-15},
      9:{cards:34,rowItems:5,tries:22,card_width:(this.width/5)-15},
      10:{cards:40,rowItems:5,tries:25,card_width:(this.width/5)-15}
      };
      this.dimens = {width: this.levels[this.state.level].card_width, height: this.levels[this.state.level].card_width};
      }

      go_next = () =>{
      this.setState({page: false, tries:0, level: 1});
      };
      go_home = () =>{
      this.setState({page: true});
      };

      tried = ()=>{
      this.setState({tries: this.state.tries+1});
      };
      level_up = ()=>{
      console.log("level up: ", this.state.level+1);
      this.setState({level: this.state.level+1, tries: 0});
      };
      level_restart = ()=>{
      console.log("level restarted: ", this.state.level);
      this.setState({level: this.state.level, tries: 0});
      }

      render() {
      if (this.state.page) {
      return (
      <View style={styles.container}>
      <Text style={styles.heading}>Cardy</Text>
      <Text>Color Memory Game for Kids</Text>
      <TouchableOpacity onPress={this.go_next}>
      <Image style={{marginBottom:30}} source={require("./assets/play.png")}></Image>
      </TouchableOpacity>
      </View>
      );
      } else {
      return (
      <View style={{flex:1}}>
      <View style={{flex:.1,alignItems: 'center',justifyContent:'flex-end',marginTop:20}}><Text style={styles.subheading}>Level {this.state.level}</Text><Text>Tries Remaining: {(this.levels[this.state.level].tries-this.state.tries)}</Text></View>

      <Cards dimens={this.dimens} cards={this.levels[this.state.level].cards} rowItems={this.levels[this.state.level].rowItems} tried={this.tried.bind(this)} level_up={this.level_up.bind(this)} level_restart={this.level_restart.bind(this)} level={this.state.level} tries={this.state.tries} total_tries={this.levels[this.state.level].tries} />

      <View style={{alignItems: 'center',flex:.1}}>
      <TouchableOpacity onPress={this.go_home}>
      <Text>← Go Home</Text>
      </TouchableOpacity>
      </View>
      </View>
      );
      }
      }
      }

      class Cards extends Component<props> {
      constructor(props){
      super(props)
      this.color='';
      this.ckey='';
      this.tries=0;
      this.matched=0;
      this.level = this.props.level;
      }

      shouldComponentUpdate(nextProps, nextState){
      if( this.level != nextProps.level || nextProps.tries==0 )
      return true;
      else return false;
      }

      do_flip = (color, ckey)=>{
      if( this.color != '' ){ // second card flip
      this.props.tried();
      this.tries++;
      if( this.color == color ){ //card matched
      this.matched++;
      this["card"+ckey].flip();
      if( this.matched == this.props.cards/2 ){
      this.tries=0;
      this.matched=0;
      alert("Level completed successfully.");
      this.props.level_up();
      }
      else if( this.tries == this.props.total_tries ){
      alert("Sorry, Level failed, try again.");
      this.tries=0;
      this.matched=0;
      this.props.level_restart();
      }
      } else { // card not matched
      var pkey = this.ckey;
      this["card"+pkey].flip();
      if( this.tries == this.props.total_tries ){
      this.tries=0;
      this.matched=0;
      alert("Sorry, Level failed, try again.");
      this.props.level_restart();
      }
      }
      this.color='';
      this.ckey='';
      } else { // first card flip
      this["card"+ckey].flip();
      this.color=color;
      this.ckey=ckey;
      }
      };

      shuffleArray = (array) => {
      for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
      }
      }

      generate_cards = ()=>{
      const inner_cards = this.props.rowItems;
      const main_loops = Math.ceil(this.props.cards/inner_cards);
      const colors = ["blue","green","red","yellow","black","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","blanchedalmond","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","yellowgreen"];
      var selected_colors = colors.slice(0, this.props.cards/2);
      selected_colors = selected_colors.concat(selected_colors);
      this.shuffleArray(selected_colors);
      var cd = 0;
      let row = ;
      let card = ;
      var list = selected_colors.map( (color, key)=> {
      if( cd == 0 ) { card = ; }
      card.push(
      <CardFlip style={this.props.dimens} key={key} ref={(card) => this["card"+key] = card}>
      <TouchableOpacity activeOpacity={1} style={this.props.dimens} onPress={() => {this.do_flip(color,key); }} >
      <Image style={this.props.dimens} source={require("./assets/robot.png")}></Image>
      </TouchableOpacity>
      <TouchableOpacity activeOpacity={0} style={[this.props.dimens]}>
      <View style={[{backgroundColor:color}, this.props.dimens]}></View>
      </TouchableOpacity>
      </CardFlip>
      );
      cd++;
      if( cd==inner_cards || key == selected_colors.length-1 ){
      cd=0;
      return <View key={key+"a"} style={{flex:1,flexDirection:'row',justifyContent:'space-evenly',alignItems: 'center'}}>{card}</View>
      }
      });
      return list;
      }
      render(){
      return (
      <View style={{flex:.8}}>
      {this.generate_cards()}
      </View>
      )
      }
      }

      const styles = StyleSheet.create({
      container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
      },
      heading:{
      fontSize: 40,
      color: 'green',
      fontWeight:'bold',
      marginBottom: 20
      },
      subheading:{
      fontSize: 30,
      color: 'green',
      fontWeight:'bold',
      marginBottom: 20
      },
      boxContainer: {
      flex: 1,
      alignItems: 'center',
      flexDirection: 'column',
      backgroundColor:'yellow'
      }
      });








      import React, { Component } from 'react';
      import {
      StyleSheet,
      Image,
      View, Dimensions, Text,
      TouchableOpacity
      } from 'react-native';

      import CardFlip from 'react-native-card-flip';

      export default class App extends Component<Props> {

      constructor(props){
      super(props)
      this.state = {
      page: true,
      level: 1,
      tries: 0,
      }
      this.width = Dimensions.get('window').width;
      this.levels = {
      1:{cards:4,rowItems:2,tries:3,card_width:(this.width/2)-15},
      2:{cards:6,rowItems:2,tries:5,card_width:(this.width/2)-15},
      3:{cards:8,rowItems:2,tries:6,card_width:(this.width/2)-70},
      4:{cards:12,rowItems:3,tries:8,card_width:(this.width/3)-50},
      5:{cards:14,rowItems:3,tries:9,card_width:(this.width/3)-50},
      6:{cards:18,rowItems:3,tries:12,card_width:(this.width/3)-50},
      7:{cards:24,rowItems:4,tries:16,card_width:(this.width/4)-15},
      8:{cards:30,rowItems:5,tries:20,card_width:(this.width/5)-15},
      9:{cards:34,rowItems:5,tries:22,card_width:(this.width/5)-15},
      10:{cards:40,rowItems:5,tries:25,card_width:(this.width/5)-15}
      };
      this.dimens = {width: this.levels[this.state.level].card_width, height: this.levels[this.state.level].card_width};
      }

      go_next = () =>{
      this.setState({page: false, tries:0, level: 1});
      };
      go_home = () =>{
      this.setState({page: true});
      };

      tried = ()=>{
      this.setState({tries: this.state.tries+1});
      };
      level_up = ()=>{
      console.log("level up: ", this.state.level+1);
      this.setState({level: this.state.level+1, tries: 0});
      };
      level_restart = ()=>{
      console.log("level restarted: ", this.state.level);
      this.setState({level: this.state.level, tries: 0});
      }

      render() {
      if (this.state.page) {
      return (
      <View style={styles.container}>
      <Text style={styles.heading}>Cardy</Text>
      <Text>Color Memory Game for Kids</Text>
      <TouchableOpacity onPress={this.go_next}>
      <Image style={{marginBottom:30}} source={require("./assets/play.png")}></Image>
      </TouchableOpacity>
      </View>
      );
      } else {
      return (
      <View style={{flex:1}}>
      <View style={{flex:.1,alignItems: 'center',justifyContent:'flex-end',marginTop:20}}><Text style={styles.subheading}>Level {this.state.level}</Text><Text>Tries Remaining: {(this.levels[this.state.level].tries-this.state.tries)}</Text></View>

      <Cards dimens={this.dimens} cards={this.levels[this.state.level].cards} rowItems={this.levels[this.state.level].rowItems} tried={this.tried.bind(this)} level_up={this.level_up.bind(this)} level_restart={this.level_restart.bind(this)} level={this.state.level} tries={this.state.tries} total_tries={this.levels[this.state.level].tries} />

      <View style={{alignItems: 'center',flex:.1}}>
      <TouchableOpacity onPress={this.go_home}>
      <Text>← Go Home</Text>
      </TouchableOpacity>
      </View>
      </View>
      );
      }
      }
      }

      class Cards extends Component<props> {
      constructor(props){
      super(props)
      this.color='';
      this.ckey='';
      this.tries=0;
      this.matched=0;
      this.level = this.props.level;
      }

      shouldComponentUpdate(nextProps, nextState){
      if( this.level != nextProps.level || nextProps.tries==0 )
      return true;
      else return false;
      }

      do_flip = (color, ckey)=>{
      if( this.color != '' ){ // second card flip
      this.props.tried();
      this.tries++;
      if( this.color == color ){ //card matched
      this.matched++;
      this["card"+ckey].flip();
      if( this.matched == this.props.cards/2 ){
      this.tries=0;
      this.matched=0;
      alert("Level completed successfully.");
      this.props.level_up();
      }
      else if( this.tries == this.props.total_tries ){
      alert("Sorry, Level failed, try again.");
      this.tries=0;
      this.matched=0;
      this.props.level_restart();
      }
      } else { // card not matched
      var pkey = this.ckey;
      this["card"+pkey].flip();
      if( this.tries == this.props.total_tries ){
      this.tries=0;
      this.matched=0;
      alert("Sorry, Level failed, try again.");
      this.props.level_restart();
      }
      }
      this.color='';
      this.ckey='';
      } else { // first card flip
      this["card"+ckey].flip();
      this.color=color;
      this.ckey=ckey;
      }
      };

      shuffleArray = (array) => {
      for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
      }
      }

      generate_cards = ()=>{
      const inner_cards = this.props.rowItems;
      const main_loops = Math.ceil(this.props.cards/inner_cards);
      const colors = ["blue","green","red","yellow","black","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","blanchedalmond","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","yellowgreen"];
      var selected_colors = colors.slice(0, this.props.cards/2);
      selected_colors = selected_colors.concat(selected_colors);
      this.shuffleArray(selected_colors);
      var cd = 0;
      let row = ;
      let card = ;
      var list = selected_colors.map( (color, key)=> {
      if( cd == 0 ) { card = ; }
      card.push(
      <CardFlip style={this.props.dimens} key={key} ref={(card) => this["card"+key] = card}>
      <TouchableOpacity activeOpacity={1} style={this.props.dimens} onPress={() => {this.do_flip(color,key); }} >
      <Image style={this.props.dimens} source={require("./assets/robot.png")}></Image>
      </TouchableOpacity>
      <TouchableOpacity activeOpacity={0} style={[this.props.dimens]}>
      <View style={[{backgroundColor:color}, this.props.dimens]}></View>
      </TouchableOpacity>
      </CardFlip>
      );
      cd++;
      if( cd==inner_cards || key == selected_colors.length-1 ){
      cd=0;
      return <View key={key+"a"} style={{flex:1,flexDirection:'row',justifyContent:'space-evenly',alignItems: 'center'}}>{card}</View>
      }
      });
      return list;
      }
      render(){
      return (
      <View style={{flex:.8}}>
      {this.generate_cards()}
      </View>
      )
      }
      }

      const styles = StyleSheet.create({
      container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
      },
      heading:{
      fontSize: 40,
      color: 'green',
      fontWeight:'bold',
      marginBottom: 20
      },
      subheading:{
      fontSize: 30,
      color: 'green',
      fontWeight:'bold',
      marginBottom: 20
      },
      boxContainer: {
      flex: 1,
      alignItems: 'center',
      flexDirection: 'column',
      backgroundColor:'yellow'
      }
      });





      import React, { Component } from 'react';
      import {
      StyleSheet,
      Image,
      View, Dimensions, Text,
      TouchableOpacity
      } from 'react-native';

      import CardFlip from 'react-native-card-flip';

      export default class App extends Component<Props> {

      constructor(props){
      super(props)
      this.state = {
      page: true,
      level: 1,
      tries: 0,
      }
      this.width = Dimensions.get('window').width;
      this.levels = {
      1:{cards:4,rowItems:2,tries:3,card_width:(this.width/2)-15},
      2:{cards:6,rowItems:2,tries:5,card_width:(this.width/2)-15},
      3:{cards:8,rowItems:2,tries:6,card_width:(this.width/2)-70},
      4:{cards:12,rowItems:3,tries:8,card_width:(this.width/3)-50},
      5:{cards:14,rowItems:3,tries:9,card_width:(this.width/3)-50},
      6:{cards:18,rowItems:3,tries:12,card_width:(this.width/3)-50},
      7:{cards:24,rowItems:4,tries:16,card_width:(this.width/4)-15},
      8:{cards:30,rowItems:5,tries:20,card_width:(this.width/5)-15},
      9:{cards:34,rowItems:5,tries:22,card_width:(this.width/5)-15},
      10:{cards:40,rowItems:5,tries:25,card_width:(this.width/5)-15}
      };
      this.dimens = {width: this.levels[this.state.level].card_width, height: this.levels[this.state.level].card_width};
      }

      go_next = () =>{
      this.setState({page: false, tries:0, level: 1});
      };
      go_home = () =>{
      this.setState({page: true});
      };

      tried = ()=>{
      this.setState({tries: this.state.tries+1});
      };
      level_up = ()=>{
      console.log("level up: ", this.state.level+1);
      this.setState({level: this.state.level+1, tries: 0});
      };
      level_restart = ()=>{
      console.log("level restarted: ", this.state.level);
      this.setState({level: this.state.level, tries: 0});
      }

      render() {
      if (this.state.page) {
      return (
      <View style={styles.container}>
      <Text style={styles.heading}>Cardy</Text>
      <Text>Color Memory Game for Kids</Text>
      <TouchableOpacity onPress={this.go_next}>
      <Image style={{marginBottom:30}} source={require("./assets/play.png")}></Image>
      </TouchableOpacity>
      </View>
      );
      } else {
      return (
      <View style={{flex:1}}>
      <View style={{flex:.1,alignItems: 'center',justifyContent:'flex-end',marginTop:20}}><Text style={styles.subheading}>Level {this.state.level}</Text><Text>Tries Remaining: {(this.levels[this.state.level].tries-this.state.tries)}</Text></View>

      <Cards dimens={this.dimens} cards={this.levels[this.state.level].cards} rowItems={this.levels[this.state.level].rowItems} tried={this.tried.bind(this)} level_up={this.level_up.bind(this)} level_restart={this.level_restart.bind(this)} level={this.state.level} tries={this.state.tries} total_tries={this.levels[this.state.level].tries} />

      <View style={{alignItems: 'center',flex:.1}}>
      <TouchableOpacity onPress={this.go_home}>
      <Text>← Go Home</Text>
      </TouchableOpacity>
      </View>
      </View>
      );
      }
      }
      }

      class Cards extends Component<props> {
      constructor(props){
      super(props)
      this.color='';
      this.ckey='';
      this.tries=0;
      this.matched=0;
      this.level = this.props.level;
      }

      shouldComponentUpdate(nextProps, nextState){
      if( this.level != nextProps.level || nextProps.tries==0 )
      return true;
      else return false;
      }

      do_flip = (color, ckey)=>{
      if( this.color != '' ){ // second card flip
      this.props.tried();
      this.tries++;
      if( this.color == color ){ //card matched
      this.matched++;
      this["card"+ckey].flip();
      if( this.matched == this.props.cards/2 ){
      this.tries=0;
      this.matched=0;
      alert("Level completed successfully.");
      this.props.level_up();
      }
      else if( this.tries == this.props.total_tries ){
      alert("Sorry, Level failed, try again.");
      this.tries=0;
      this.matched=0;
      this.props.level_restart();
      }
      } else { // card not matched
      var pkey = this.ckey;
      this["card"+pkey].flip();
      if( this.tries == this.props.total_tries ){
      this.tries=0;
      this.matched=0;
      alert("Sorry, Level failed, try again.");
      this.props.level_restart();
      }
      }
      this.color='';
      this.ckey='';
      } else { // first card flip
      this["card"+ckey].flip();
      this.color=color;
      this.ckey=ckey;
      }
      };

      shuffleArray = (array) => {
      for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
      }
      }

      generate_cards = ()=>{
      const inner_cards = this.props.rowItems;
      const main_loops = Math.ceil(this.props.cards/inner_cards);
      const colors = ["blue","green","red","yellow","black","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","blanchedalmond","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","yellowgreen"];
      var selected_colors = colors.slice(0, this.props.cards/2);
      selected_colors = selected_colors.concat(selected_colors);
      this.shuffleArray(selected_colors);
      var cd = 0;
      let row = ;
      let card = ;
      var list = selected_colors.map( (color, key)=> {
      if( cd == 0 ) { card = ; }
      card.push(
      <CardFlip style={this.props.dimens} key={key} ref={(card) => this["card"+key] = card}>
      <TouchableOpacity activeOpacity={1} style={this.props.dimens} onPress={() => {this.do_flip(color,key); }} >
      <Image style={this.props.dimens} source={require("./assets/robot.png")}></Image>
      </TouchableOpacity>
      <TouchableOpacity activeOpacity={0} style={[this.props.dimens]}>
      <View style={[{backgroundColor:color}, this.props.dimens]}></View>
      </TouchableOpacity>
      </CardFlip>
      );
      cd++;
      if( cd==inner_cards || key == selected_colors.length-1 ){
      cd=0;
      return <View key={key+"a"} style={{flex:1,flexDirection:'row',justifyContent:'space-evenly',alignItems: 'center'}}>{card}</View>
      }
      });
      return list;
      }
      render(){
      return (
      <View style={{flex:.8}}>
      {this.generate_cards()}
      </View>
      )
      }
      }

      const styles = StyleSheet.create({
      container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
      },
      heading:{
      fontSize: 40,
      color: 'green',
      fontWeight:'bold',
      marginBottom: 20
      },
      subheading:{
      fontSize: 30,
      color: 'green',
      fontWeight:'bold',
      marginBottom: 20
      },
      boxContainer: {
      flex: 1,
      alignItems: 'center',
      flexDirection: 'column',
      backgroundColor:'yellow'
      }
      });






      react-native






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 19 '18 at 16:04









      Optimus Medialinkers

      1




      1
























          1 Answer
          1






          active

          oldest

          votes


















          0















          You're initializing the state in the constructor, which only runs once at the time of component mounting. So when the state of parent component is changing, it is passing the props to the child, but the constructor of the child component is not running in that case, therefore the child component state is not behaving as you're expecting.




          Something like this will work. Define componentWillReceiveprops in your child component, and setState if the newly received props are different than the previous one.



          I'm using a library lodash for comparing object, arrays and so on. I recommend you to us it



          Example



          import React, {Component} from 'react'
          import _ from 'lodash';

          class ChildComponent extends Component{
          componentWillReceiveProps(nextProps){
          if(!_.isEqual(this.props.something, nextProps.something) && Boolean(nextProps)){
          this.setState({something: nextProps.something})
          }
          }
          render(){
          return(

          )
          }
          }


          Note: Try not to setState into the componentWillReceiveProps or componentDidUpdate without a condition to ensure it won't lead you to infinite loop of setting state






          share|improve this answer





















          • I am already using shouldComponentUpdate to check if this component should update or not, when I have updated to use componentWillReceiveProps then it is updating component always even though it is having check. shouldComponentUpdate(nextProps, nextState){ if( this.level != nextProps.level || nextProps.tries==0 ) return true; else return false; }
            – Optimus Medialinkers
            Nov 20 '18 at 7:22












          • you have written the wrong condition in if, it should be this.props.level not just this.level. Also, add the function in your code that I have written.
            – Siraj
            Nov 20 '18 at 8:11










          • I have updated this code but still not working, I have updated this.level to this.state.level and have put it in state of this child component: componentWillReceiveProps(nextProps){ if( this.state.ilevel != nextProps.level ){ this.setState({ilevel: this.state.ilevel++}); } else if ( nextProps.tries==0 ){ this.setState({ilevel: this.state.ilevel}); } }
            – Optimus Medialinkers
            Nov 26 '18 at 13:06











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53378517%2freact-native-imported-component-not-initializing-its-state-on-parent-state-chang%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0















          You're initializing the state in the constructor, which only runs once at the time of component mounting. So when the state of parent component is changing, it is passing the props to the child, but the constructor of the child component is not running in that case, therefore the child component state is not behaving as you're expecting.




          Something like this will work. Define componentWillReceiveprops in your child component, and setState if the newly received props are different than the previous one.



          I'm using a library lodash for comparing object, arrays and so on. I recommend you to us it



          Example



          import React, {Component} from 'react'
          import _ from 'lodash';

          class ChildComponent extends Component{
          componentWillReceiveProps(nextProps){
          if(!_.isEqual(this.props.something, nextProps.something) && Boolean(nextProps)){
          this.setState({something: nextProps.something})
          }
          }
          render(){
          return(

          )
          }
          }


          Note: Try not to setState into the componentWillReceiveProps or componentDidUpdate without a condition to ensure it won't lead you to infinite loop of setting state






          share|improve this answer





















          • I am already using shouldComponentUpdate to check if this component should update or not, when I have updated to use componentWillReceiveProps then it is updating component always even though it is having check. shouldComponentUpdate(nextProps, nextState){ if( this.level != nextProps.level || nextProps.tries==0 ) return true; else return false; }
            – Optimus Medialinkers
            Nov 20 '18 at 7:22












          • you have written the wrong condition in if, it should be this.props.level not just this.level. Also, add the function in your code that I have written.
            – Siraj
            Nov 20 '18 at 8:11










          • I have updated this code but still not working, I have updated this.level to this.state.level and have put it in state of this child component: componentWillReceiveProps(nextProps){ if( this.state.ilevel != nextProps.level ){ this.setState({ilevel: this.state.ilevel++}); } else if ( nextProps.tries==0 ){ this.setState({ilevel: this.state.ilevel}); } }
            – Optimus Medialinkers
            Nov 26 '18 at 13:06
















          0















          You're initializing the state in the constructor, which only runs once at the time of component mounting. So when the state of parent component is changing, it is passing the props to the child, but the constructor of the child component is not running in that case, therefore the child component state is not behaving as you're expecting.




          Something like this will work. Define componentWillReceiveprops in your child component, and setState if the newly received props are different than the previous one.



          I'm using a library lodash for comparing object, arrays and so on. I recommend you to us it



          Example



          import React, {Component} from 'react'
          import _ from 'lodash';

          class ChildComponent extends Component{
          componentWillReceiveProps(nextProps){
          if(!_.isEqual(this.props.something, nextProps.something) && Boolean(nextProps)){
          this.setState({something: nextProps.something})
          }
          }
          render(){
          return(

          )
          }
          }


          Note: Try not to setState into the componentWillReceiveProps or componentDidUpdate without a condition to ensure it won't lead you to infinite loop of setting state






          share|improve this answer





















          • I am already using shouldComponentUpdate to check if this component should update or not, when I have updated to use componentWillReceiveProps then it is updating component always even though it is having check. shouldComponentUpdate(nextProps, nextState){ if( this.level != nextProps.level || nextProps.tries==0 ) return true; else return false; }
            – Optimus Medialinkers
            Nov 20 '18 at 7:22












          • you have written the wrong condition in if, it should be this.props.level not just this.level. Also, add the function in your code that I have written.
            – Siraj
            Nov 20 '18 at 8:11










          • I have updated this code but still not working, I have updated this.level to this.state.level and have put it in state of this child component: componentWillReceiveProps(nextProps){ if( this.state.ilevel != nextProps.level ){ this.setState({ilevel: this.state.ilevel++}); } else if ( nextProps.tries==0 ){ this.setState({ilevel: this.state.ilevel}); } }
            – Optimus Medialinkers
            Nov 26 '18 at 13:06














          0












          0








          0







          You're initializing the state in the constructor, which only runs once at the time of component mounting. So when the state of parent component is changing, it is passing the props to the child, but the constructor of the child component is not running in that case, therefore the child component state is not behaving as you're expecting.




          Something like this will work. Define componentWillReceiveprops in your child component, and setState if the newly received props are different than the previous one.



          I'm using a library lodash for comparing object, arrays and so on. I recommend you to us it



          Example



          import React, {Component} from 'react'
          import _ from 'lodash';

          class ChildComponent extends Component{
          componentWillReceiveProps(nextProps){
          if(!_.isEqual(this.props.something, nextProps.something) && Boolean(nextProps)){
          this.setState({something: nextProps.something})
          }
          }
          render(){
          return(

          )
          }
          }


          Note: Try not to setState into the componentWillReceiveProps or componentDidUpdate without a condition to ensure it won't lead you to infinite loop of setting state






          share|improve this answer













          You're initializing the state in the constructor, which only runs once at the time of component mounting. So when the state of parent component is changing, it is passing the props to the child, but the constructor of the child component is not running in that case, therefore the child component state is not behaving as you're expecting.




          Something like this will work. Define componentWillReceiveprops in your child component, and setState if the newly received props are different than the previous one.



          I'm using a library lodash for comparing object, arrays and so on. I recommend you to us it



          Example



          import React, {Component} from 'react'
          import _ from 'lodash';

          class ChildComponent extends Component{
          componentWillReceiveProps(nextProps){
          if(!_.isEqual(this.props.something, nextProps.something) && Boolean(nextProps)){
          this.setState({something: nextProps.something})
          }
          }
          render(){
          return(

          )
          }
          }


          Note: Try not to setState into the componentWillReceiveProps or componentDidUpdate without a condition to ensure it won't lead you to infinite loop of setting state







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 19 '18 at 18:32









          Siraj

          1,57311631




          1,57311631












          • I am already using shouldComponentUpdate to check if this component should update or not, when I have updated to use componentWillReceiveProps then it is updating component always even though it is having check. shouldComponentUpdate(nextProps, nextState){ if( this.level != nextProps.level || nextProps.tries==0 ) return true; else return false; }
            – Optimus Medialinkers
            Nov 20 '18 at 7:22












          • you have written the wrong condition in if, it should be this.props.level not just this.level. Also, add the function in your code that I have written.
            – Siraj
            Nov 20 '18 at 8:11










          • I have updated this code but still not working, I have updated this.level to this.state.level and have put it in state of this child component: componentWillReceiveProps(nextProps){ if( this.state.ilevel != nextProps.level ){ this.setState({ilevel: this.state.ilevel++}); } else if ( nextProps.tries==0 ){ this.setState({ilevel: this.state.ilevel}); } }
            – Optimus Medialinkers
            Nov 26 '18 at 13:06


















          • I am already using shouldComponentUpdate to check if this component should update or not, when I have updated to use componentWillReceiveProps then it is updating component always even though it is having check. shouldComponentUpdate(nextProps, nextState){ if( this.level != nextProps.level || nextProps.tries==0 ) return true; else return false; }
            – Optimus Medialinkers
            Nov 20 '18 at 7:22












          • you have written the wrong condition in if, it should be this.props.level not just this.level. Also, add the function in your code that I have written.
            – Siraj
            Nov 20 '18 at 8:11










          • I have updated this code but still not working, I have updated this.level to this.state.level and have put it in state of this child component: componentWillReceiveProps(nextProps){ if( this.state.ilevel != nextProps.level ){ this.setState({ilevel: this.state.ilevel++}); } else if ( nextProps.tries==0 ){ this.setState({ilevel: this.state.ilevel}); } }
            – Optimus Medialinkers
            Nov 26 '18 at 13:06
















          I am already using shouldComponentUpdate to check if this component should update or not, when I have updated to use componentWillReceiveProps then it is updating component always even though it is having check. shouldComponentUpdate(nextProps, nextState){ if( this.level != nextProps.level || nextProps.tries==0 ) return true; else return false; }
          – Optimus Medialinkers
          Nov 20 '18 at 7:22






          I am already using shouldComponentUpdate to check if this component should update or not, when I have updated to use componentWillReceiveProps then it is updating component always even though it is having check. shouldComponentUpdate(nextProps, nextState){ if( this.level != nextProps.level || nextProps.tries==0 ) return true; else return false; }
          – Optimus Medialinkers
          Nov 20 '18 at 7:22














          you have written the wrong condition in if, it should be this.props.level not just this.level. Also, add the function in your code that I have written.
          – Siraj
          Nov 20 '18 at 8:11




          you have written the wrong condition in if, it should be this.props.level not just this.level. Also, add the function in your code that I have written.
          – Siraj
          Nov 20 '18 at 8:11












          I have updated this code but still not working, I have updated this.level to this.state.level and have put it in state of this child component: componentWillReceiveProps(nextProps){ if( this.state.ilevel != nextProps.level ){ this.setState({ilevel: this.state.ilevel++}); } else if ( nextProps.tries==0 ){ this.setState({ilevel: this.state.ilevel}); } }
          – Optimus Medialinkers
          Nov 26 '18 at 13:06




          I have updated this code but still not working, I have updated this.level to this.state.level and have put it in state of this child component: componentWillReceiveProps(nextProps){ if( this.state.ilevel != nextProps.level ){ this.setState({ilevel: this.state.ilevel++}); } else if ( nextProps.tries==0 ){ this.setState({ilevel: this.state.ilevel}); } }
          – Optimus Medialinkers
          Nov 26 '18 at 13:06


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53378517%2freact-native-imported-component-not-initializing-its-state-on-parent-state-chang%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          MongoDB - Not Authorized To Execute Command

          Npm cannot find a required file even through it is in the searched directory

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith