无法使用react update addon更新redux状态

时间:2016-05-20 14:12:42

标签: reactjs redux react-redux

以下是我在console.log中的reducer状态

state:{getMessagesRequest: false,projects:[]}

projects数组包含以下结构的对象

{messages:Array[0],userid:'foo',username:'bar'}

reducer使用以下大小写将消息对象推送到messages数组中:

  case GET_PROJECT_MESSAGES_SUCCESS:
      console.log('GET_PROJECT_MESSAGES_SUCCESS invoked: ',action)
      let target = state.projects.findIndex((project) => {
          return project.project_id == action.project_id
        })
    action.data.map((message) => {
      console.log('TARGET IS : ',target)
      console.log('MESSSAGE IS: ',message)
      return update(state,{
        projects:{
          [target]:{
            messages:{
              $push:[message]
            }
          }
        }
      })
    })

console.log显示目标(target = 0)和消息(作为对象)的有效值

但减速器显示以下错误

Uncaught TypeError: Cannot read property 'messages' of undefined

这表明它打破了[目标] ..但目标具有正确的价值,所以我不确定问题可能在哪里。

我有一个额外的reducer几乎做了类似的事情,但我只有一个消息对象推送到项目数组。减速器适用于这种情况:

   case NEW_CHAT_MESSAGE: //use parseInt instead of ==
      target = state.projects.findIndex((project) => {
        return project.project_id == action.data.projectid
      })
      return update(state,{
        projects:{
          [target]:{
            messages:{
              $push:[action.data]
            }
          }
        }
      })

action.data是一个对象。第一个reducer处理一个对象数组 - 因此是map函数。

问题出在哪里?

更新:它非常奇怪,但是一旦NEW_CHAT_MESSAGE执行完毕,第二个reducer GET_PROJECT_MESSAGES_SUCCESS也会被调用。错误由new_chat reducer发送。国家仍然没有得到更新。由于第一个reducer的多次返回,这可能是一个问题吗?(因为我循环遍历这些对象?)

1 个答案:

答案 0 :(得分:0)

这样做而不是循环遍历数组

  return update(state,{
      projects:{
        [target]:{
          messages:{
            $set:action.data
          }
        }
      }
    })
相关问题