[英]Not able to change state on event trigger in react native
我在react-native-voice
上調用事件以識別語音並調用API並設置狀態。 但是,當我為狀態數組設置新值時,該數組僅具有新值,而不具有先前值。 這是我的代碼
constructor(props){
super(props);
this.state = {
results = [];
}
Voice.onSpeechResults = this.onSpeechResults;
}
我有一個事件被觸發來調用這樣的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
});
});
};
但是當設置狀態時,我只能將新元素而不是先前的狀態推入數組。 我嘗試使用concat
, spread
和設置一個新數組。 卡住了,請幫忙。 :(
首先聲明您的狀態,例如:
this.state = {
results: []; // Don't use = for properties
}
第二個注意事項是,如果將setState()
與現有值相同的值,則不會設置狀態(並調用render函數)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.