【发布时间】:2018-01-24 08:19:17
【问题描述】:
我正在尝试将 redux 状态显示到我的 react 组件中。我的根 reducer 看起来是这样的:
index.js
import { combineReducers } from 'redux';
import PostReducer from './PostsReducer';
import { reducer as formReducer} from 'redux-form';
import CategoriesReducer from './CategoriesReducer';
import CommentsReducer from './CommentsReducer';
const rootReducer = combineReducers({
posts: PostReducer,
categories: CategoriesReducer,
comments: CommentsReducer,
form : formReducer
});
export default rootReducer;
现在,我在访问我的 cmets 状态时遇到问题。我的 CommentsReducer 减速器如下所示:
CommentsReducer.js
import { FETCH_COMMENTS } from '../actions/comment_action';
export default function(state={}, action) {
switch (action.type) {
case FETCH_COMMENTS:
return {comments: {...state.comments, ...action.payload.data}};
default:
return state;
}
}
在我的组件中,我试图在我的 mapStateToProps 方法中获取 state,如下所示:
function mapStateToProps({ posts, comments }, ownProps) {
return {
post: posts[ownProps.match.params.id],
comment: comments[ownProps.match.params.id]};
}
现在,在我的渲染函数中,如果我尝试将 cmets 状态设置为 {this.props.cmets} ,我收到 null。我的意思是它不显示任何内容。我该如何继续?
EDIT 2条件渲染:
{
(createStoreWithMiddleware.getState().comments) ?
<div>
{this.props.comment}
</div>
:
<div>
Null
</div>
}
EDIT 3:API 服务器中的 Comment.js 文件。
const defaultData = {
"894tuq4ut84ut8v4t8wun89g": {
id: '894tuq4ut84ut8v4t8wun89g',
parentId: "8xf0y6ziyjabvozdd253nd",
timestamp: 1468166872634,
body: 'Hi there! I am a COMMENT.',
author: 'thingtwo',
voteScore: 6,
deleted: false,
parentDeleted: false
},
"8tu4bsun805n8un48ve89": {
id: '8tu4bsun805n8un48ve89',
parentId: "8xf0y6ziyjabvozdd253nd",
timestamp: 1469479767190,
body: 'Comments. Are. Cool.',
author: 'thingone',
voteScore: -5,
deleted: false,
parentDeleted: false
}
}
而我的API端点描述如下:
GET /comments/:id
USAGE:
Get the details for a single comment
【问题讨论】:
-
你的组件连接到 redux 存储了吗?
-
@TimH 是的,我做到了。我使用了这行代码
export default connect(mapStateToProps, { fetchPost, deletePost, editPost, fetchComments })(PostDetail); -
好的,这条线应该没问题。您能否检查一下您的 mapStateToProps 是否正常工作?也许发布一些console.logs
-
@TimH 我尝试在我的渲染方法中获取状态,如下所示:
console.log(createStoreWithMiddleware.getState());它显示了 cmets 在 cmets 状态下的显示。我在上面添加了一个屏幕截图。你能有一个看? -
我猜这很可能是因为初始状态 cmets 在 redux 存储中为 null 并且直到 cmets 可从 FETCH_COMMENTS 操作中获得
标签: javascript reactjs redux