我有一个表中显示的对象列表。编辑列表中的项目时,除非刷新页面,否则不会显示更新的项目。
清单减少器
export const eaCodesReducer = (state = initialState.eaCodes, action) => {
switch (action.type) {
case "GET_EA_CODES": {
return {
...state,
eaCodes: action.payload
}
}
default: {
return state
}
}
}
单个项目的减缩器
export const eaSingleEaCodeReducer = (state = initialState.eaCode, action) => {
switch (action.type) {
case "UPDATE_EA_CODE": {
return {
...state,
eaCode: action.payload
}
}
default:
return state
}
}
然后我如何告诉它更新eaCodes列表以合并单个项目更改?
export const eaSingleEaCodeReducer = (state = initialState.eaCode, action) => {
switch (action.type) {
case "UPDATE_EA_CODE": {
return {
...state,
eaCode: action.payload,
eaCodes: [...state.eaCodes, action.payload]
}
}
default:
return state
}
}
您的eaCodesReducer
应该返回一个数组而不是对象。因此,新状态始终是数组中的前一项以及新项,因此您应该映射到绑定到商店的组件中的这一状态。当您在商店中更新此特定状态时,表中的更新应自动反映。
// this should be an array also
export const eaCodesReducer = (state = initialState.eaCodes, action) => {
switch (action.type) {
case "GET_EA_CODES": {
// should be an array
return [
...state,
action.payload
]
}
default: {
return state
}
}
}
希望这会有所帮助!
@@ D10S的想法正确,但导致应用崩溃。而不是添加额外的reducer-如果初始放置请求成功,我更新了操作以调用reducer:
export const updateEnforcementActionCode = (id, updateTypeObj) => {
return dispatch => {
return axios.put(`/api/enforcementactions/codes/${id}`, updateTypeObj)
.then(res => {
dispatch({ type: "UPDATE_EA_CODE", payload: res.data })
if (res.status === 200) {
return axios.get('/api/enforcementactions/codes')
.then(res => {
dispatch({ type: "GET_EA_CODES", payload: res.data })
})
}
}).catch(err => {
dispatch({ type: "GET_ERRORS", payload: err.response.message })
})
}
}
这似乎有点多余。如果有人建议这样做,那么我很开放。