[英]React hooks are overwritting object array
I'm trying to code a chatbot interface using React hooks and Wit.ai.我正在尝试使用 React hooks 和 Wit.ai 编写一个聊天机器人界面。
I have tried setting the messages imperatively (setMessages([...messages, currentValue]) but that doesn't work either. Here's the code:我试过命令式设置消息 (setMessages([...messages, currentValue]) 但这也不起作用。这是代码:
const [currentValue, setCurrentValue] = useState('');
const [messages, setMessages] = useState([]);
const handleChange = (event) => {
setCurrentValue(event.target.value); // handling input change
}
const sendMessage = (event) => {
event.preventDefault();
if (currentValue.trim() !== '' || currentValue.trim().length > 1) {
witClient.message(currentValue).then(data => {
setMessages(() => [...messages, {text: currentValue, sender: 'user'}]); // here i set the user message
if (data.entities) {
setMessages(() => [...messages, {text: 'message from bot', sender: 'bot'}]); // this line seems to overwrite the user message with the bot message
setCurrentValue('');
}
});
}
document.querySelector('input').focus();
}
When I handle the bots response it overwrites the users message.当我处理机器人响应时,它会覆盖用户消息。
Since you are relying on prior values you can use functional pattern for setting state like below:由于您依赖于先验值,您可以使用功能模式来设置状态,如下所示:
Docs: https://reactjs.org/docs/hooks-reference.html#functional-updates文档: https : //reactjs.org/docs/hooks-reference.html#functional-updates
setMessages((priorMessages) => [...priorMessages, {text: currentValue, sender: 'user'}]);
======================================
if (data.entities) {
setMessages((priorMessages) => [...priorMessages, {text: 'message from bot', sender: 'bot'}]);
When you access messages
after the if statement
you're actually overwritting the first changes, cause [...messages, {text: currentValue, sender: 'user'}]
will only be reflected in the next render
.当您在
if statement
之后访问messages
,您实际上是在覆盖第一次更改,导致[...messages, {text: currentValue, sender: 'user'}]
只会反映在下一个render
。 Set your changes all at once to prevent this一次性设置所有更改以防止出现这种情况
const sendMessage = (event) => {
event.preventDefault();
if (currentValue.trim() !== '' || currentValue.trim().length > 1) {
witClient.message(currentValue).then(data => {
let newMessages = [...messages, {text: currentValue, sender: 'user'}]
if (data.entities) {
newMessages = newMessages.concat({text: 'message from bot', sender: 'bot'})
setCurrentValue('');
}
setMessages(messages)
});
}
document.querySelector('input').focus();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.