我有一个“ fetchComments”和“ fetchCommentsById”。当前,当我console.log props.comments时,我记录了所有注释和注释62,是否可以将两者分开?
const MainPage = (props) => {
useEffect(() => {
props.fetchComments();
props.fetchCommentById(62);
}, []);
console.log("all comments: ", props.comments);
return (
<>
<div>MainPage</div>
</>
);
};
const mapStateToProps = (state) => {
return { comments: state.comments };
};
export default connect(mapStateToProps, { fetchComments, fetchCommentById })(
MainPage
);
这是我的评论减少器。
export default (state = [], action) => {
switch (action.type) {
case FETCH_COMMENTS:
return [...state, action.payload];
case FETCH_COMMENT_BY_ID:
return action.payload;
default:
return state;
}
};
答案 0 :(得分:0)
在化简器中,存储一个既包含完整注释又包含commentById的对象,而不是仅将注释存储在数组中。
主页组件:
const MainPage = (props) => {
useEffect(() => {
props.fetchComments();
props.fetchCommentById(62);
}, []);
console.log("all comments: ", props.comments);
console.log("comment by id: ", props.commentById);
return (
<>
<div>MainPage</div>
</>
);
};
const mapStateToProps = (state) => {
return {
commentById: state.comments.commentById,
comments: state.comments.comments
};
};
export default connect(mapStateToProps, { fetchComments, fetchCommentById })(
MainPage
);
像这样更改减速器:
const initialState = {
comments: [],
commentById: ''
}
export default (state = initialState, action) => {
switch (action.type) {
case FETCH_COMMENTS:
return {...state, comments: action.payload}; // assuming you are returning an array from the server
case FETCH_COMMENT_BY_ID:
return {...state, commentById: action.payload};
default:
return state;
}
};