你好,我的聊天机器人的逻辑有问题 基本上我是用户键入一些内容,然后发送带有消息的调度,并使用状态定义为等待响应 并将我的状态isTyping设置为true
几秒钟后在settimout中使用了答案,但是我忘了一些东西,当我输入很多文本时,我并没有得到所有答案并取消了动画
我发现错误的原因是useEffect,但我不知道如何解决它: 我永远无法进入自己的其中一种情况: 如果(isTyping){ 要么 如果(等待){ 我真的不知道该怎么解决 请帮助我:(
在示例中:
https://codesandbox.io/s/cool-water-1dwqx
代码:
const UserText = props => {
return (
<Styled.MessageWrapper user={true}>
<Styled.ChatMessage user={true}>{props.children}</Styled.ChatMessage>
</Styled.MessageWrapper>
);
};
const BotText = props => {
const memoedText = useMemo(() => props.children, []);
console.log(props.isTyping);
return (
<>
<Styled.MessageWrapper>
<Styled.BotImg src={BotLogo} />
<Styled.ChatMessage>
<Styled.TypingWrapper show={props.isTyping}>
<span />
<span />
<span />
</Styled.TypingWrapper>
{!props.isTyping && memoedText}
</Styled.ChatMessage>
</Styled.MessageWrapper>
</>
);
};
const Chat = () => {
const dispatch = useDispatch();
const ChatReducer = useSelector(state => state.Chat);
const { messages } = ChatReducer;
const [text, setText] = useState("");
const [auxText, setAuxText] = useState("");
const [wait, setWait] = useState(false);
const [isTyping, setIsTyping] = useState(false);
const handleClick = () => {
dispatch(sendMessage(text));
setWait(true);
setAuxText(text);
setText("");
};
useEffect(() => {
if (isTyping) {
dispatch(sendResponse([auxText]));
const timeoutId = setTimeout(() => {
setIsTyping(false);
setWait(false);
}, 3000);
}
}, [isTyping]);
useEffect(() => {
if (wait) {
setIsTyping(true);
}
}, [wait]);
console.log("chat", isTyping);
return (
<Styled.ChatBox>
<Styled.ChatLog>
{messages.map((message, index) => (
<>
{message.text ? (
<Styled.MessageFlexColumn key={index}>
{message.type === "user" ? (
<UserText key={index}>{message.text}</UserText>
) : (
<BotText
key={index}
isTyping={isTyping && index === messages.length - 1}
>
{message.text}
</BotText>
)}
</Styled.MessageFlexColumn>
) : (
""
)}
</>
))}
</Styled.ChatLog>
<Styled.ChatInput>
<textarea
disabled={ChatReducer.waitResponse ? true : false}
onKeyPress={e => {
if (e.key === "Enter") {
e.preventDefault();
}
if (e.key === "Enter") {
console.log("ae");
handleClick();
}
}}
value={text}
onChange={e => setText(e.target.value)}
placeholder="Digite aqui sua mensagem"
/>
<button onClick={handleClick} />
</Styled.ChatInput>
</Styled.ChatBox>
);
};
操作:
export const sendMessage = text => ({
type: ON_MESSAGE,
text
});
export const botMessage = text => ({
type: BOT_MESSAGE,
text
});
export const sendResponse = text => {
return dispatch => {
text.map((message, index) => {
dispatch(botMessage(message));
});
};
gif问题:
基本上,在键入文字时,我会取消另一个的动画