我正在将redux与react一起使用,并且尝试将从api中获得的对象数组附加到我的redux状态(即对象数组)
这是我的减速器...
import { GET_BOOKS } from "../actions/types";
const initialState = {
books: [
0:{},
1:{},
]
};
export default function(state = initialState, action) {
switch (action.type) {
case GET_BOOKS:
console.log(action.payload.results);
return { ...state };
default:
return state;
}
}
我的api返回
results : [
0: {somevalue},
1: {somevalue}
]
我不知道如何将这些值分布到新数组中。
答案 0 :(得分:1)
只需分配该属性,它将覆盖旧属性。
export default function(state = initialState, action) {
switch (action.type) {
case GET_BOOKS:
console.log(action.payload.results);
// spread current state and inaddition to that set new books data
// which overwrites books property from old state
return { ...state, books : action.payload.results };
// spread --^^^^^^^^^^^^^^^^^^^^^^^^^^^---
default:
return state;
}
}
更新::如果要将其与现有连接起来,请执行以下操作。
export default function(state = initialState, action) {
switch (action.type) {
case GET_BOOKS:
console.log(action.payload.results);
return { ...state, books : [...state.books, ...action.payload.results] };
default:
return state;
}
}
仅供参考::...state
部分用于复制其他状态属性(假设存在其他状态值)
答案 1 :(得分:0)
您需要连接来自api的当前状态和数据
return { books: [...state.books, ...action.payload.results] };
完整代码
import { GET_BOOKS } from "../actions/types";
const initialState = { books: [] };
export default (state: Object = initialState, action: Object) => {
switch (action.type) {
case GET_BOOKS:
return { books: [...state.books, ...action.payload.results] };
default:
return state;
}
};