温馨提示:本文翻译自stackoverflow.com,查看原文请点击:reactjs - React / Redux / Send text typed on textarea to the store
reactjs redux

reactjs - React / Redux /将在textarea上键入的文本发送到商店

发布于 2020-04-08 09:53:47

我的动作:

export const ON_MESSAGE = 'ON_MESSAGE';

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

我的减速器:

const initalState = [{ text: [] }];

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

export default messageReducer;

我的代码:

const Chat = props => {
  const dispatch = useDispatch();
  const messages = useSelector(state => state.Chat);

  return (
    <Styled.ChatBox>
      <Styled.ChatHeader>
        <p>Chat Bot</p>
        <div>
          <FontAwesomeIcon icon={faAngleDown} size="1x" color="white" />
          <FontAwesomeIcon icon={faTimes} size="1x" color="white" />
        </div>
      </Styled.ChatHeader>
      <Styled.ChatLog></Styled.ChatLog>
      <Styled.ChatInput>
        <textarea placeholder="Digite aqui sua mensagem" />
        <button onClick={dispatch(sendMessage)}>
          <FontAwesomeIcon icon={faPaperPlane} size="lg" color="black" />
        </button>
      </Styled.ChatInput>
    </Styled.ChatBox>
  );
};

export { Chat };

您好,基本上我想知道如何将文本中键入的值发送到我的redux商店

以及如何在组件中显示此键入的值

> <Styled.ChatLog> </ Styled.ChatLog>

基本上,每个消息都应生成一个div(组件)

> <Styled.ChatMessage />

查看更多

提问者
user12356906
被浏览
14
Amit Chauhan 2020-01-31 21:13

您可以将消息存储在本地状态,然后将其发送到有效负载。

const Chat = props => {
  const dispatch = useDispatch();
  const messages = useSelector(state => state.Chat);
  const [text, setText] = React.useState("");

  return (
    <Styled.ChatBox>
      <Styled.ChatHeader>
        <p>Chat Bot</p>
        <div>
          <FontAwesomeIcon icon={faAngleDown} size="1x" color="white" />
          <FontAwesomeIcon icon={faTimes} size="1x" color="white" />
        </div>
      </Styled.ChatHeader>
      <Styled.ChatLog>
        {messages.map( message => (
          <Styled.ChatMessage>
            {message.text}
          </Styled.ChatMessage>
        )}
      </Styled.ChatLog>
      <Styled.ChatInput>
        <textarea value={text} onChange={e => setText(e.target.value)} placeholder="Digite aqui sua mensagem" />
        <button onClick={() => dispatch(sendMessage({ text }))}>
          <FontAwesomeIcon icon={faPaperPlane} size="lg" color="black" />
        </button>
      </Styled.ChatInput>
    </Styled.ChatBox>
  );
};

export { Chat };