【问题标题】:unable to update redux state using react update addon无法使用反应更新插件更新 redux 状态
【发布时间】:2016-05-20 14:12:41
【问题描述】:

以下是来自 console.log 的减速器状态

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

projects 数组具有以下结构的对象

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

reducer 使用以下情况将消息对象推送到消息数组中:

  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) 和消息(它是一个对象)的有效值

但是reducer显示以下错误

Uncaught TypeError: Cannot read property 'messages' of undefined

这表明它在 [target] 上的中断.. 但 target 具有正确的值,所以我不确定问题可能出在哪里。

我有一个额外的 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 函数。

问题可能出在哪里?

update :这很奇怪,但是一旦GET_PROJECT_MESSAGES_SUCCESS 的执行完成,第二个减速器NEW_CHAT_MESSAGE 也会被调用。错误是由 new_chat reducer 发送的。状态仍然没有得到更新。由于第一个减速器的多次返回,这可能是一个问题吗?(因为我正在循环对象?)

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    结束了这样做而不是遍历数组

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

    【讨论】:

      猜你喜欢
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      • 2020-04-11
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      • 2021-12-02
      相关资源
      最近更新 更多