Javascript 一次更新多个Redux存储项目

Javascript 一次更新多个Redux存储项目,javascript,redux,redux-store,Javascript,Redux,Redux Store,在我的Redux存储中,我有一个线程数组和一个回复数组。每个回复都有一个线程ID,用于将其与线程关联。从数据库获取线程时,回复计数是返回的属性之一,并且该计数显示在网页中线程旁边 当用户添加新答复时,我的问题就会出现。API返回的信息足够我将新回复添加到回复集合中。但是我还想增加线程的reply count属性,它位于线程数组中。我该怎么做 以下是我的(简化)减速器: constthread=(state={},action)=>{ 让nextState=state if(action.typ

在我的Redux存储中,我有一个线程数组和一个回复数组。每个回复都有一个线程ID,用于将其与线程关联。从数据库获取线程时,回复计数是返回的属性之一,并且该计数显示在网页中线程旁边

当用户添加新答复时,我的问题就会出现。API返回的信息足够我将新回复添加到回复集合中。但是我还想增加线程的reply count属性,它位于线程数组中。我该怎么做

以下是我的(简化)减速器:

constthread=(state={},action)=>{
让nextState=state
if(action.type==C.POST\u消息){
nextState=action.payload
}
返回下一状态
}
const threads=(state=initialState.threads,action)=>{
让nextState=state
if(action.type==C.POST\u消息){
nextState=[线程(null,操作),…状态]
}
返回下一状态
}
const reply=(state={},action)=>{
让nextState=state
if(action.type==C.POST\u回复){
nextState=action.payload
}
返回下一状态
}
常量回复=(状态=初始状态。回复,操作)=>{
让nextState=state
if(action.type==C.POST\u回复){
nextState=[…状态,操作.有效负载]
}
返回下一状态

}
在您的情况下,当在某处创建回复时,您正在发送一个操作(我想是“POST\u reply”操作)

请记住,应用程序的每个减速机中都有一个已调度的操作,因此,如果要更新线程状态,只需相应地响应线程减速机中的
POST\u 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
}

谢谢马西尼萨!顺便说一句,你的代码有一点不准确+应从切片函数参数中删除1和-1。