React Js / Redux Middlware聊天机器人

时间:2020-02-01 19:51:25

标签: javascript reactjs react-redux

你好,基本上我有一个聊天机器人,我在其中将文本发送到我的商店并在我的聊天正文中显示

很好,但是我想做以下事情: 当用户发送文本时,立即在聊天正文中显示该文本

然后为机器人设置一个响应时间,但是我对如何执行此操作以及如何构造机器人的响应感到困惑

代码:

操作:

export const ON_MESSAGE = 'ON_MESSAGE';
export const BOT_MESSAGE = 'BOT_MESSAGE';

export const sendMessage = (text, user = true) => ({
  type: ON_MESSAGE,
  payload: { text, user },
});

export const botMessage = (text, bot = true) => ({
  type: BOT_MESSAGE,
  payload: { text, bot },
});


export  const checkMessage = (text, user = true) => {
  return (dispatch)  => {
      dispatch(sendMessage());
      // response

      if(text === 'a'){

      }
  }
}

减速器:

import { ON_MESSAGE } from 'Redux/actions/Chat_action';

const initalState = [
  {
    text: 'Mdsdassssssssssadas',
    user: false,
    bot: false,
  },
];

const messageReducer = (state = initalState, action) => {
  switch (action.type) {
    case ON_MESSAGE:
      return [...state, action.payload];
    default:
      return state;
  }
};

export default messageReducer;

jsx代码:

const Chat = props => {
  const dispatch = useDispatch();
  const messages = useSelector(state => state.Chat);
  const widget = useSelector(state => state.WidgetStatus.widgetStatus);
  const [text, setText] = useState('');
  const handleClick = () => {
    dispatch(sendMessage(text));
    setText('');
  };

  return (
    <Styled.ChatBox widget={widget}>
      <Styled.ChatHeader>
        <p>Chat Bot</p>
        <div>
          <FontAwesomeIcon
            onClick={id => dispatch({ type: 'TOGGLE_WIDGET' })}
            icon={faAngleDown}
            size="1x"
            color="white"
          />
          <FontAwesomeIcon
            onClick={id => dispatch({ type: 'TOGGLE_WIDGET' })}
            icon={faTimes}
            size="1x"
            color="white"
          />
        </div>
      </Styled.ChatHeader>
      <Styled.ChatLog>

        {messages.map(message => (
          <Styled.MessageWrapper user={message.user}>
            <Styled.BotImg src={BotLogo} user={message.user} />
            <Styled.ChatMessage user={message.user}>
              {message.text}
            </Styled.ChatMessage>
          </Styled.MessageWrapper>
        ))}
      </Styled.ChatLog>
      <Styled.ChatInput>
        <textarea
          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}>
          <FontAwesomeIcon icon={faPaperPlane} size="lg" color="black" />
        </button>
      </Styled.ChatInput>
    </Styled.ChatBox>
  );
};

img: enter image description here

0 个答案:

没有答案