将对象添加到 Redux 中的数组?
Add object to array in Redux?
我正在尝试向名为 allLogbooks 的数组添加一个元素。该数组包含名为 Logbook 的对象。我的问题是,我如何适应代码,以便将新元素添加到在我的 reducer 中声明的数组中?这是我的初始状态:
const initialState = {
isFetching: false,
error: undefined,
isRegistered: false,
isUpdated: false,
hasChecked: false,
isError: false,
registerStepOne: true,
registerStepTwo: false,
registerStepThree: false,
registerStepFour: false,
logbooks: undefined,
allLogbooks: [],
userInfo: undefined,
logbookAddSuccess: false,
newLogbook: undefined,
graphFilter: 1
}
这是我的减速器:
case ADD_LOGBOOK_SUCCESS:
allLogbooks.push(action.newLogbook);
return {
...state,
isFetching: false,
logbookAddSuccess: true,
isUpdated: true,
isError: false,
}
这是我的行动:
function addLogbookSuccess(newLogbook) {
return {
type: ADD_LOGBOOK_SUCCESS
}
}
然后我对 nodejs 服务器进行 POST 调用,如果成功,它将在其中响应一条消息,以及刚刚创建的日志。下面的数据就是这样returns:
{
"success": true,
"logbook": {
"created_by": "",
"created_at": "",
"_id": "",
"__v": 0
}
}
然后我在 API 调用中调度,这样:
.then(data => data.json())
.then(json => {
Keyboard.dismiss();
dispatch(addLogbookSuccess(json.logbook));
})
.catch(err => dispatch(addLogbookFailed(err)))
我已经通过使用 AsyncStorage 代替它来访问我所有观点中的数组,但我知道这是错误的。
我有点难以理解你的问题,所以我已经尽力了。如果我的回答完全不对,请告诉我。
你的减速器:
case ADD_LOGBOOK_SUCCESS: {
const newLogbook = action.payload;
return {
...state,
isFetching: false,
logbookAddSuccess: true,
isUpdated: true,
isError: false,
allLogBooks: [
...state.allLogBooks,
newLogbook
]
}
}
您的操作:
function addLogbookSuccess(newLogbook) {
return {
type: ADD_LOGBOOK_SUCCESS,
payload: newLogbook
}
}
我正在尝试向名为 allLogbooks 的数组添加一个元素。该数组包含名为 Logbook 的对象。我的问题是,我如何适应代码,以便将新元素添加到在我的 reducer 中声明的数组中?这是我的初始状态:
const initialState = {
isFetching: false,
error: undefined,
isRegistered: false,
isUpdated: false,
hasChecked: false,
isError: false,
registerStepOne: true,
registerStepTwo: false,
registerStepThree: false,
registerStepFour: false,
logbooks: undefined,
allLogbooks: [],
userInfo: undefined,
logbookAddSuccess: false,
newLogbook: undefined,
graphFilter: 1
}
这是我的减速器:
case ADD_LOGBOOK_SUCCESS:
allLogbooks.push(action.newLogbook);
return {
...state,
isFetching: false,
logbookAddSuccess: true,
isUpdated: true,
isError: false,
}
这是我的行动:
function addLogbookSuccess(newLogbook) {
return {
type: ADD_LOGBOOK_SUCCESS
}
}
然后我对 nodejs 服务器进行 POST 调用,如果成功,它将在其中响应一条消息,以及刚刚创建的日志。下面的数据就是这样returns:
{
"success": true,
"logbook": {
"created_by": "",
"created_at": "",
"_id": "",
"__v": 0
}
}
然后我在 API 调用中调度,这样:
.then(data => data.json())
.then(json => {
Keyboard.dismiss();
dispatch(addLogbookSuccess(json.logbook));
})
.catch(err => dispatch(addLogbookFailed(err)))
我已经通过使用 AsyncStorage 代替它来访问我所有观点中的数组,但我知道这是错误的。
我有点难以理解你的问题,所以我已经尽力了。如果我的回答完全不对,请告诉我。
你的减速器:
case ADD_LOGBOOK_SUCCESS: {
const newLogbook = action.payload;
return {
...state,
isFetching: false,
logbookAddSuccess: true,
isUpdated: true,
isError: false,
allLogBooks: [
...state.allLogBooks,
newLogbook
]
}
}
您的操作:
function addLogbookSuccess(newLogbook) {
return {
type: ADD_LOGBOOK_SUCCESS,
payload: newLogbook
}
}