简体   繁体   中英

React Native - Why is this state object empty in function?

I have this React-Native component, which renders an image gallery, in a list. So it's invoked once per each item on that parent list. It receives two props, "etiqueta" which has the title of the item, and "galleries", which is an array of galleries (javascript literals). I know it should only receive the gallery that we need to render, but I couldn't do it, so for now, I'm sending all the galleries and filtering them in this component.

Problem: when I console.log the state in ComponentDidMount everything looks good, state.entries has the gallery that need to be rendered. But when I try to access it in get Example2() it returns an empty array. I'm not sure why this is happening.

And also, for some reason, the console.log in get Example2() keeps running again and again in the console. Why is this happening?

This is the gallery I'm trying to use: https://github.com/archriss/react-native-snap-carousel

Thank you for your time of course, I hope I'm clear enough, I'm new to React.

class EtiquetaDetail extends Component {

  constructor(props) {
    super(props);

    this.state = {
      slider1ActiveSlide: 0,
      slider1Ref: null,
      entries: [],
      isMounted: false
    };
  }

  componentDidMount() {

    let etiqueta_id = this.props.etiqueta.id ;

    if ( this.props.etiqueta ) {

      // select the gallery we need to render
      gallery = this.props.galleries.find(function (obj) {
        return obj.id_gal === etiqueta_id;
      });

      ENTRIES1 = JSON.parse( gallery.data );

      this.setState = {
        slider1ActiveSlide: 0,
        slider1Ref: null,
        entries: ENTRIES1,
        isMounted: true
      };
      console.log(this.state); // this outputs everything as expected

    }

  }

get example2 () {
  console.log(this.state.entries); // returns 0 
    return (
        <View>
            <Carousel
              data={ this.state.entries }
            />
        </View>
    );
}

  render() {

    const etiqueta = this.props;

    const { title } = this.props.etiqueta;

    return (
      <Card>
        <CardSection>
          <View>
            <Text>{title.rendered}</Text>
          </View>
        </CardSection>

        <SafeAreaView>
            <View}>
                <ScrollView>
                    { this.example2 }
                </ScrollView>
            </View>
        </SafeAreaView>

      </Card>
    )
  };

};

When you need to update the state outside of the constructor, use this.setState , to let React know it needs to do a re-render.

this.setState({
  slider1ActiveSlide: 0,
  slider1Ref: null,
  entries: ENTRIES1,
  isMounted: true
})

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