0

目前,我正在实施聊天。用户按下聊天按钮后,应用程序会将用户导航到聊天组件。聊天内容将简单地存储在 firebase 中,并且需要 chatId 来识别哪个聊天属于用户。

由于导航时不知道如何通过props,所以决定将 CurrentChatId 保存在 AsyncStorage 中。导航到 Chat 组件后,它将从 AsyncStorage 获取 CurrentChatId,以便我可以将聊天内容与 firebase 进行映射。

但是,我收到_this3.navigateTo is not a function以下代码的错误:

let ref = FirebaseClient.database().ref('/Chat'); 
ref.orderByChild("chatId").equalTo(chatId).once("value", function(snapshot) {

    chatId = taskId + "_" + user1Id + "_" + user2Id;
    if (snapshot.val() == null) {
        ref.push({
            chatId: chatId,
            taskId: taskId,
            user1Id: user1Id,
            user2Id: user2Id,
        })
    }
    try {
        AsyncStorage.setItem("CurrentChatId", chatId).then(res => { 
            this.navigateTo('chat');
        });
    } catch (error) {
        console.log('AsyncStorage error: ' + error.message);
    }
}

该函数navigateTo是从 NativeBase 的演示应用程序中复制的

import { actions } from 'react-native-navigation-redux-helpers';
import { closeDrawer } from './drawer';

const {
  replaceAt,
  popRoute,
  pushRoute,
} = actions;

export default function navigateTo(route, homeRoute) {
  return (dispatch, getState) => {
    const navigation = getState().cardNavigation;
    const currentRouteKey = navigation.routes[navigation.routes.length - 1].key;

    dispatch(closeDrawer());

    if (currentRouteKey !== homeRoute && route !== homeRoute) {
      dispatch(replaceAt(currentRouteKey, { key: route, index: 1 }, navigation.key));
    } else if (currentRouteKey !== homeRoute && route === homeRoute) {
      dispatch(popRoute(navigation.key));
    } else if (currentRouteKey === homeRoute && route !== homeRoute) {
      dispatch(pushRoute({ key: route, index: 1 }, navigation.key));
    }
  };
}
4

2 回答 2

1

您应该将此绑定到包含try & catch的函数。最好的做法是在组件的构造函数中添加这个绑定:

constructor(props) {
  super(props);
  this.myFunctoin = this.myfuction.bind(this);
}
于 2017-04-21T16:16:49.867 回答
0

最后,我解决了这个问题。真的是因为this.navigateTo('chat');在里面function(snapshot)

ref.orderByChild("chatId").equalTo(chatId).once("value", function(snapshot) {

    chatId = taskId + "_" + user1Id + "_" + user2Id;
    if (snapshot.val() == null) {
        ref.push({
            chatId: chatId,
            taskId: taskId,
            user1Id: user1Id,
            user2Id: user2Id,
        })
    }
}
try {
    AsyncStorage.setItem("CurrentChatId", chatId).then(res => { 
        this.navigateTo('chat');
    });
} catch (error) {
    console.log('AsyncStorage error: ' + error.message);
}

把它从函数里拿出来就可以解决问题了。

于 2017-04-21T16:45:40.303 回答