目前,我正在使用react redux的组合来处理我的通知逻辑。我想执行的行为是,每当一个人点击到一个列表中的对象,我会抓住这个ID,把它发送到我的后台,并改变领域。is_read = True
. 然而 , 而不是调用api再次抓取我所有的通知,只是为了显示 , 该对象已被读取 , 我希望从数组中定位下来的对象,并改变其字段 is_read=True
一旦我的操作返回成功。
这是我的一些代码。
notifications: [{
id(pin):1,
title(pin):"no title available...",
datetime(pin):"2020-06-12T10:33:27.173774Z",
is_read = false,
},
{
id(pin):2,
title(pin):"no title available...",
datetime(pin):"2020-06-12T10:33:27.173774Z",
is_read = false,
},
],
//I have 2 functions here , one is to handle 1 click , the 2nd is to handle a 'clear all' button
export function* workerReadNotification(action) {
yield put({ type: 'SHOW_LOADER_COMPONENT', loading: 'notifications' })
const data = yield call(() => axiosInstance.get(`/notifications/${notification_id}`))
yield put({ type: "UPDATE_NOTIFICATION_DATA", payload: data.data })
yield put({ type: 'HIDE_LOADER_COMPONENT', loading: 'notifications' })
if (action.message) {
yield put({ type: "CREATE_MESSAGE", message: action.message })
}
}
export function* workerReadAllNotification(action) {
yield put({ type: 'SHOW_LOADER_COMPONENT', loading: 'notifications' })
const data = yield call(() => axiosInstance.post(`/notifications/readall/`,action.data))
yield put({ type: "UPDATE_NOTIFICATION_DATA", payload: data.data })
yield put({ type: 'HIDE_LOADER_COMPONENT', loading: 'notifications' })
if (action.message) {
yield put({ type: "CREATE_MESSAGE", message: action.message })
}
}
const updateNotificationData = (state, action) => {
return updateObject(state, {
//logic here to replace the fields
});
}
我的问题是,什么是最好的方式来完成这2个更新操作?
你可以通过传递需要更新的对象的id来使用下面的实用方法。
let notifications = [{
"id(pin)":1,
"title(pin)":"no title available...",
"datetime(pin)":"2020-06-12T10:33:27.173774Z",
is_read: false,
},
{
"id(pin)":2,
"title(pin)":"no title available...",
"datetime(pin)":"2020-06-12T10:33:27.173774Z",
is_read: false,
},
];
const updateObject = (data, id) => {
return data.map(d => {
if(id === d["id(pin)"]) {
return {
...d,
is_read: true
}
} else return {...d}
})
}
console.log(updateObject(notifications, 1))
如果你想一次更新多个对象,那么可以使用下面的方法。
let notifications = [{
"id(pin)":1,
"title(pin)":"no title available...",
"datetime(pin)":"2020-06-12T10:33:27.173774Z",
is_read: false,
},
{
"id(pin)":2,
"title(pin)":"no title available...",
"datetime(pin)":"2020-06-12T10:33:27.173774Z",
is_read: false,
},
{
"id(pin)":3,
"title(pin)":"no title available...",
"datetime(pin)":"2020-06-12T10:33:27.173774Z",
is_read: false,
}
];
const updateObjectByIds = (data, idArray) => {
return data.map(d => {
if(idArray.includes(d["id(pin)"])) {
return {
...d,
is_read: true
}
} else return {...d}
})
}
console.log(updateObjectByIds(notifications, [1, 2]))
希望对你有所帮助。