我在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和设置一个新的数组。卡住了,请帮帮忙。:(
发布于 2019-08-07 17:26:25
首先像这样声明你的状态:
this.state = {
results: []; // Don't use = for properties
}第二,请注意,如果您使用与已有的值相同的值进行渲染,则不会设置状态(并调用setState()函数)。
https://stackoverflow.com/questions/57390420
复制相似问题