我有一个在ReactJS中制作表情符号的功能
addEmoji = (emoji) =>{
//with array function
let newEmoji = {
id: emoji.id,
count: 1
};
if(this.state.emojis.filter(emoji =>{
if(emoji.id === newEmoji.id){
this.increment(newEmoji);
}
}))
console.log(this.state.emojis)
this.setState( prevState => ({
emojis: [...prevState.emojis, newEmoji],
showEmoji: true
}))
它接受来自emoji-mart节点模块的自定义emoji对象
我现在的问题是,我想检查对象是否已经显示,如果有则增加计数。
我做了这种增量方法,其中每个表情符号对象的计数都增加了。我的问题是我必须改变整个数组中一个对象的状态,这给我带来了困难
increment = (newEmoji) =>{
console.log(id);
let count = newEmoji.count
count = newEmoji.count+1
console.log(newEmoji.count)
this.setState(
{emoji: newEmoji} // how do i change the state of that one obejct inside the array
)
console.log(this.state.emoji.count)
}
编辑: 我提供了状态,以查看是否已设置状态。
this.state= {
emojis: []
}
答案 0 :(得分:1)
您可以在遍历整个数组的同时重新创建整个数组,并在必要时更改表情符号的数量,两只鸟和一块石头。这是未经测试的版本:
const AgeIntentHandler = {
canHandle(handlerInput) {
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& handlerInput.requestEnvelope.request.intent.name === 'AgeIntent'
&& sessionAttributes.state !== 'WEIGHT';
},
handle(handlerInput) {
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
sessionAttributes.state = 'WEIGHT';
handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
const speechText = 'Age intent is called!';
return handlerInput.responseBuilder
.speak(speechText)
.withSimpleCard('Hello World', speechText)
.getResponse();
},
};
const WeightIntentHandler = {
canHandle(handlerInput) {
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& handlerInput.requestEnvelope.request.intent.name === 'WeightIntent'
&& sessionAttributes.state === 'WEIGHT';
},
handle(handlerInput) {
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
sessionAttributes.state = '';
handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
const speechText = 'Weight intent is called!';
return handlerInput.responseBuilder
.speak(speechText)
.withSimpleCard('Hello World', speechText)
.getResponse();
},
};