温馨提示:本文翻译自stackoverflow.com,查看原文请点击:reactjs - React js and Redux : Objects are not valid as a React child
reactjs redux

reactjs - React js和Redux:对象作为React子对象无效

发布于 2020-04-04 10:41:39

行动;

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>

查看更多

提问者
user12356906
被浏览
15
Craig Ayre 2020-01-31 23:12

问题是您的操作需要单独的参数,但您传递的是单个对象

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))