一次更新多个 Redux 商店项目

Updating multiple Redux store items in one go

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

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

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

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' 动作)。

请记住,在应用程序的每个 reducer 中都有一个分派操作,因此如果您想更新线程状态,您只需相应地响应线程 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
}

现在您可以使用回复中的信息更新特定话题。 请记住,每次更新时都必须 return 一个新对象。

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
}