一次更新多个Redux商店项目

时间:2017-09-09 09:46:50

标签: javascript redux redux-store

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

当用户添加新回复时,我的挑战就会浮出水面。 API返回足够的信息,以便将新回复添加到回复集合中。但我还想增加线程的回复计数属性,该属性位于线程数组中。我该怎么做?

这些是我的(简化)减速器:



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
}




1 个答案:

答案 0 :(得分:1)

在您的情况下,您在某处创建回复时调度操作(我猜想是'POST_REPLY'操作)。

请记住,在应用程序的每个reducer中都可以使用调度操作,因此如果要更新线程状态,则只需相应地响应线程减速器中的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
}