我的行动:
export const ON_MESSAGE = 'ON_MESSAGE';
export const sendMessage = (text, sender = 'user') => ({
type: ON_MESSAGE,
payload: { text, sender },
});我的reducer:
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 />发布于 2020-01-31 20:49:09
您可以将消息存储在本地状态,并将其发送到有效负载。
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 };https://stackoverflow.com/questions/60004157
复制相似问题