因此,在重构基于类的聊天机器人组件以使用反应钩子的过程中,我遇到了useState钩子覆盖状态中对象的问题。这会导致仅机器人响应显示在 UI 中。当我与机器人聊天时,UI 中会显示用户输入的闪存,然后被聊天机器人响应覆盖。这是代码:
export const Chatbot = () => {
const [messages, setMessages] = useState([]);
const [value, setValue] = useState("");
async function df_text_query(text) {
let says = {
speaks: "me",
message: {
text: {
text
}
}
};
setMessages([...messages, says]);
const res = await axios.post("/api/df_text_query", {
text,
userID: cookies.get("userID")
});
// Handles fullfillment routes for dialogflow
res.data.fulfillmentMessages.forEach(message => {
says = {
speaks: "bot",
message
};
setMessages([...messages, says]);
});
}
const handleChange = e => {
setValue(e.target.value);
};
const handleSubmit = e => {
e.preventDefault();
if (value !== "") {
const message = value.split();
df_text_query(message);
}
setValue("");
};
const handleButtonSend = async event => {
const eventText = event.target.innerText;
await setValue(eventText);
const message = value.split();
await df_text_query(message);
await setValue("");
};
return (
<div>
<div>chatbot code here</div>
</div>
);
};
是否可以在同一个异步函数中两次像这样编写 useState? 如果不是,您如何建议我重构此代码,以便消息状态返回交替对象数组,例如:
[{says: {
speaks: "me",
message: {
text: {
text
}
}
}
},
{says: {
speaks: "bot",
message: {
text: {
text
}
}
}
},
{says: {
speaks: "me",
message: {
text: {
text
}
}
}
},
{says: {
speaks: "bot",
message: {
text: {
text
}
}
}
}
]```
Any answer would be very much appreciated. I've been stuck on this problem for a while now. If you need more information I'm happy to provide!
Cheers,
Jacks
尝试这样的事情:
async function df_text_query(text) {
let says = [{
speaks: "me",
message: {
text: {
text
}
}
}];
const res = await axios.post("/api/df_text_query", {
text,
userID: cookies.get("userID")
});
// Handles fullfillment routes for dialogflow
let saysBatch = [says, ...res.data.fulfillmentMessages.map(message => ({
speaks: "bot",
message
}))];
setMessages([...messages, ...saysBatch]);