行动;
export const ON_MESSAGE = 'ON_MESSAGE';
export const sendMessage = (text, sender = 'user') => ({
type: ON_MESSAGE,
payload: { text, sender },
});
减速器:
import { ON_MESSAGE } from 'Redux/actions/Chat_action';
import { act } from 'react-dom/test-utils';
const initalState = [{ text: [] }];
const messageReducer = (state = initalState, action) => {
switch (action.type) {
case ON_MESSAGE:
return [...state, action.payload];
default:
return state;
}
};
export default messageReducer;
联合减速机:
import Chat from 'Redux/reducers/Chat_reducer';
export default combineReducers({
Chat,
});
商店:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './rootReducer';
export default function configureStore(initialState) {
return createStore(rootReducer, applyMiddleware(thunk));
}
和代码:
const Chat = props => {
const dispatch = useDispatch();
const messages = useSelector(state => state.Chat);
const [text, setText] = React.useState('');
console.log(messages);
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>
);
};
基本上,我的初始消息通常显示在我的聊天正文中,但是当我键入一条消息并使用分派时,出现以下错误:
未捕获的错误:对象作为React子对象无效(找到:带有键{text}的对象)。
和
上面的错误发生在组件中:
问题在这里:
<Styled.ChatLog>
{messages.map(message => (
<Styled.ChatMessage>{message.text}</Styled.ChatMessage>
))}
</Styled.ChatLog>
问题是您的操作需要单独的参数,但您传递的是单个对象
export const sendMessage = (text, sender = 'user') => ({
type: ON_MESSAGE,
payload: { text, sender },
});
dispatch(sendMessage({ text }))
因此,减速器的形状实际上[{ text: { text: "..." } }]
是[{ text: "..." }]
这意味着message.text
实际上是一个object { text: '...' }
,导致错误:
<Styled.ChatMessage>{message.text}</Styled.ChatMessage>
要解决此问题,您需要将值作为单个参数传递给操作,如下所示:
dispatch(sendMessage(text))
糟糕,您可以再帮我吗?我对如何发送设置的消息感到困惑,因为该消息是与减速器相关的用户发送的,如果它不是机器人,则可能必须制作一个中间件来返回