【问题标题】:React hooks are overwritting object arrayReact 钩子正在覆盖对象数组
【发布时间】:2019-09-03 13:12:56
【问题描述】:

我正在尝试使用 React 钩子和 Wit.ai 编写聊天机器人界面。

我尝试过强制设置消息 (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();
}

当我处理机器人响应时,它会覆盖用户消息。

【问题讨论】:

  • 附注如果有人想知道我的 wit ai 访问令牌,我可以将其发送给您

标签: node.js reactjs react-hooks wit.ai


【解决方案1】:

由于您依赖先前的值,您可以使用功能模式来设置状态,如下所示:

文档: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'}]);

【讨论】:

【解决方案2】:

当您在if statement 之后访问messages 时,您实际上覆盖了第一个更改,因为[...messages, {text: currentValue, sender: 'user'}] 只会反映在下一个render 中。一次性设置所有更改以防止这种情况发生

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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-04
    • 2020-09-21
    • 2022-11-22
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 2014-07-21
    相关资源
    最近更新 更多