我创建了动作和reducer来将消息(数组)保存在redux存储中。我已经为此创建了动作和reducer,但是一旦将数据存储在redux store中,如何显示数据呢?
reducer.js:
import { SAVE_ITEMS, SAVE_MESSAGES} from '../actions/types';
const initialState = {
messages: [],
items: []
}
export default function (state = initialState, action) {
switch (action.type) {
case SAVE_MESSAGES:
return {
...state,
messages: action.payload
};
default:
return state;
}
}
action.js:
import { SAVE_MESSAGES } from './types';
export const saveMessages = (messages) => ({
type: SAVE_MESSAGES,
payload: { messages }
})
在组件中,我这样保存数据:
this.props.saveMessages(data)
以及连接:
const mapStateToProps = state => ({
author: state.chat.author,
messages: state.chat.messages,
message: state.chat.message
})
export default connect (mapStateToProps, { saveAuthor, saveMessages, deleteAuthor, deleteMessage })(Chat);
在CombineReducer中,即index.js:
import {combineReducers} from 'redux';
import users from './loginReducer'
import allusers from './userReducer'
import chatReducer from './chatReducer'
export default combineReducers({
users: users,
allusers: allusers,
chat: chatReducer
})
如果我现在console.log(this.props)
,请参见下面的屏幕截图:
如果我现在console.log(this.props.messages)
,请参见下面的屏幕截图:
现在,我想映射消息数据并显示它,但是如果执行this.props.messages.messages[0]
->错误this.props.messages[0]
给出了未定义,则会出现错误。
屏幕截图:(redux工具)
答案 0 :(得分:1)
我认为首先您可以检查this.props.messages.messages
是否未定义,然后再使用map()
打印如下消息:
{this.props.messages && this.props.messages.messages && this.props.messages.messages.map(function(msg,i) {
return (
<p>{msg.message}</p>
)
})}