Reactjs 如何使用react将对象推入数组
这是我的初始状态常量对象,我试图在注释中添加一个新的注释项,但这段代码并没有将我的对象推到我做错的地方,提前谢谢Reactjs 如何使用react将对象推入数组,reactjs,redux,react-redux,Reactjs,Redux,React Redux,这是我的初始状态常量对象,我试图在注释中添加一个新的注释项,但这段代码并没有将我的对象推到我做错的地方,提前谢谢 export const comments = []; export const BlogPostReducer = (state = comments, action) => { switch (action.type) { case 'ADD_COMMENT': return [
export const comments = [];
export const BlogPostReducer = (state = comments, action) => {
switch (action.type) {
case 'ADD_COMMENT':
return [
...state,
{
name: action.comment.name,
subject: action.comment.subject,
message: action.comment.message
}
];
default:
return state;
}
};
after i used see console here...still im getting empty state
要推送新对象,您需要按
return [
...state,
{
name: action.comment.name,
subject: action.comment.subject,
message: action.comment.message
}
];
这将创建新的数组,将对象推入其中并返回它如果要以不变的方式将其添加到数组中,则应使用'concat' 试试下面的代码
export const comments = [];
export const BlogPostReducer = (state = comments, action) => {
switch (action.type) {
case 'ADD_COMMENT':
return state.concat({name: action.comment.name,subject: action.comment.subject,message: action.comment.message});
default:
return state;
}
};
这样我就做到了,
const addCommentToArray = (state, action) => {
return [...state.comments, {
name: action.comment.name,
subject: action.comment.subject,
message: action.comment.message
}];
}
export const BlogPostReducer = (state = initialState, action) => {
switch (action.type) {
case 'ADD_COMMENT':
return Object.assign({}, state, { comments: addCommentToArray(state, action) });
default:
return state;
}
};
您需要将注释作为参数传递到存储,并附加到注释中
export const BlogPostReducer = (state, action) => {
switch (action.type) {
case 'ADD_COMMENT':
let { comments } = state;
comments = comments || [];
comments.push(action.comment);
state.comments = comments;
return state;
default:
return state;
}
};
@Hana Alaydrus你能帮我吗Hi你能检查一下我在使用你的代码后附加在我的问题上的控制台图像吗这是一个非常糟糕的方法,因为它会改变状态@库马尔的答案要好得多。