[英]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. 我在
react-native-voice
上调用事件以识别语音并调用API并设置状态。 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. 我有一个事件被触发来调用这样的API。
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. 我尝试使用
concat
, spread
和设置一个新数组。 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). 第二个注意事项是,如果将
setState()
与现有值相同的值,则不会设置状态(并调用render函数)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.