1

我目前正在开发react-native具有聊天功能的应用程序。我redux用来存储我的状态。因此,在按下发送按钮发送消息后,会调用一个操作将消息发送到 firebase 并随后将其显示在屏幕上。

我当前的问题是,虽然我调用的动作调度了正确的类型/有效负载,但另一个类型/有效负载也在被调度,它没有在被调用的动作中调度。显然,正在以某种方式调用另一个包含类型/有效负载的动作。

未被调用的操作代码如下:

const getChatData = (chatIDs, userName, uid) => async dispatch => {
  console.log('hasdhkhwerljlkbgkanndhadndngknnjnjsnfjskdnfjsuvhshdifhuishiduhfuishdkfnkjsndf')
  const chatData = []
  for (const key of chatIDs) {

     [...]

        // get message
        firebase.database().ref('messages/' + key)
          .orderByChild('timestamp').limitToLast(1)
          .on('child_added', snapshot => {
            const { text, timestamp, user } = snapshot.val();
            const { name } = user;

            chatData.push({ key, members: displayNameArray, text, timestamp, name })
            dispatch({
              type: GET_CHAT_DATA,
              payload: chatData
            })
          })
      })
  }
}

正如我所说,GET_CHAT_DATA即使没有调用此操作,也会分派类型。此外,console.log 没有显示长的测试消息,这应该意味着这个动作没有被调用,对吧?

什么可能导致这种奇怪的行为?

太感谢了!

4

1 回答 1

1

因此,即使您没有执行该功能,但在那里您在 firebase 上注册了一个事件

 .on('child_added', snapshot => { })

现在,只要child_added触发此事件,就会执行处理程序。这就是您的调度程序正在运行的原因,因为它在事件处理程序中。

 firebase.database().ref('messages/' + key)
          .orderByChild('timestamp').limitToLast(1)
          .on('child_added', snapshot => {
            // this is the event handler which is executing
            // when the "child_added" event is triggered
            const { text, timestamp, user } = snapshot.val();
            const { name } = user;

            chatData.push({ key, members: displayNameArray, text, timestamp, name })
            dispatch({
              type: GET_CHAT_DATA,
              payload: chatData
            })
          })
      })
于 2019-02-12T17:01:15.750 回答