-1

在我的 Redux 商店中,我有一组线程和一组回复。每个回复都有一个线程 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
}

4

1 回答 1

1

在您的情况下,当在某处创建回复时,您正在调度一个动作(我想是“POST_REPLY”动作)。

请记住,在应用程序的每个 reducer 中都可以使用已调度的操作,因此如果您想更新线程状态,您只需相应地响应POST_REPLY线程 reducer 中的操作。

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
}
于 2017-09-09T10:23:52.740 回答