在我的 Redux 存储中,我有一个线程数组和一个回复数组。每个Reply都有一个线程ID来将其与一个线程关联起来。从数据库获取线程时,回复计数是返回的属性之一,并且该计数与线程一起显示在网页中。
当用户添加新回复时,我的挑战就会出现。 API 返回足够的信息,以便我将新回复添加到回复集合中。但我还想增加线程的回复计数属性,该属性位于线程数组内。我该怎么做?
这些是我的(简化的)Reducers:
const thread = (state = {}, action) => {
let nextState = state
if (action.type === C.POST_MESSAGE) {
nextState = action.payload
}
return nextState
}
const threads = (state = initialState.threads, action) => {
let nextState = state
if (action.type === C.POST_MESSAGE) {
nextState = [thread(null, action), ...state]
}
return nextState
}
const reply = (state = {}, action) => {
let nextState = state
if (action.type === C.POST_REPLY) {
nextState = action.payload
}
return nextState
}
const replies = (state = initialState.replies, action) => {
let nextState = state
if (action.type === C.POST_REPLY) {
nextState = [...state, action.payload]
}
return nextState
}
在您的情况下,当在某处创建回复时,您正在调度一个操作(我想是“POST_REPLY”操作)。
请记住,应用程序的每个减速器中都可以使用分派操作,因此如果您想更新线程状态,只需相应地响应线程减速器中的
POST_REPLY
操作即可。
const threads = (state = initialState.threads, action) => {
... // other logic to update the threads list
if(action.type === 'POST_REPLY') {
// increment the reply count here and return the new thread list
// action.payload would be the reply object in this case
}
... // other logic to update the threads list
}
现在您可以使用回复中的信息更新特定主题。 请记住,每次更新时都必须返回一个新对象。
const threads = (state = initialState.threads, action) => {
... // other logic to update the threads list
if(action.type === 'POST_REPLY') {
const reply = action.payload;
const index = state.findIndex(i => i.id === reply.threadId) // index of the thread in the array
const newThread = {...state[index], replies: state[index].replies + 1}
return [
...state.slice(0, index), // copy threads before this index
newThread, // the updated thread
...state.slice(index) // copy threads after this index
]
}
... // other logic to update the threads list
}