简体   繁体   中英

Not able to change state on event trigger in react native

I am calling an event on react-native-voice to recognize the speech and calling an API and setting the state. But when I am setting a new value to a state array the array only have the new value instead of having the previous value. This is my code

constructor(props){
  super(props);
  this.state = {
  results = [];
}
Voice.onSpeechResults = this.onSpeechResults;
}

and I have a event which is been triggered to call an API like this.

onSpeechResults = e => {
        this._startRecognizing();
        //var joined = this.state.results.concat();
        getProductListingService(e.value[0]).then(data=>{
            let demoVar = Object.values(data);
            var newArray = this.state.results;
            newArray.push(demoVar[1]);
            this.setState({
                results:newArray
            })
           this.setState({
               show:true
           });
        });

    };

But when setting the state I am only able to get the new element been pushed into the array instead of the previous state. I have tried using concat , spread , and setting a new array. Stuck, Please help. :(

First declare your state like:

this.state = {
  results: []; // Don't use = for properties
}

second notice that if you setState() with same values that it already has, it doesn't set the state(and call render function).

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