我的动作:
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 />
您可以将消息存储在本地状态,然后将其发送到有效负载。
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 };
我在<button onClick = {dispatch(sendMessage({text}))}>上收到此错误:重新渲染过多。React限制了渲染次数以防止无限循环。
更新的答案,您需要在其中创建箭头函数()=> dispatch(sendMessage({text})
谢谢兄弟,您能帮我什么更好的方式在chatlog的ChatMessage组件中显示键入的消息
您可以映射消息并呈现ChatMessage组件。我更新了答案。请检查
我收到此错误:×错误:对象作为React子对象无效(找到:带有键{text}的对象)。如果要渲染子级集合,请改用数组。