我想与我现有的react-redux项目进行实时聊天。但是它给出了错误:
MessageList.js:16 Uncaught TypeError: Cannot read property 'map' of undefined
MessageList.js有两个组件:MessageForm.js
用于发送消息和消息列表的消息表单是列表组件
这是MessageList.js组件代码
import React from 'react';
import MessageForm from 'components/chat/MessageForm';
import { addMessage, deleteMessage } from 'actions/Chatactions';
import { connect } from 'react-redux';
const MessageList = ({messageList, dispatch}) => (
<div>
<h1>Mesajlar</h1>
<MessageForm onChange={e => {
if(e.keyCode == 13){
dispatch(addMessage(e.target.value))
e.target.value = ''
}
}}/>
{messageList.map((messageForm, index) => <p key={index}>{messageForm} <button onClick={e => {
dispatch(deleteMessage(index))
}}>X</button></p>)}
</div>
)
function mapStateToProps(messageList) {
return {
messageList
}
}
export default connect(mapStateToProps)(MessageList)
export default MessageList;
这里是这里是MessageForm.js组件代码
import React from 'react';
import { connect } from 'react-redux';
const MessageForm = ({onChange}) => (
<div>
<h3>New</h3>
<input type="text" placeholder="Type your message here" onKeyUp={onChange}/>
</div>
)
export default MessageForm
这是我的行动
export function addMessage(MessageForm){
return {
type: 'addMessage',
MessageForm
}
}
export function deleteMessage(index){
return {
type: 'deleteMessage',
index
}
}
这是我的reducer(MessageList.js)
import Immutable from 'immutable'
export default (state = Immutable.List(), action) => {
switch(action.type) {
case 'addMessage':
return state.unshift(action.MessageForm)
case 'deleteMessage':
return state.filter((MessageForm, index) => index !== action.index)
default:
return state
}
}
这是我的商店(store.js与index.html的路径相同)
import { createStore } from 'redux';
import MessageList from './reducers/MessageList'
export default createStore(MessageList)