AsyncStorage.setItem之后的导航:_this3.navigateTo不是函数

时间:2017-04-21 16:08:26

标签: firebase react-native native-base

目前,我正在实施聊天。用户按下聊天按钮后,应用程序会将用户导航到聊天组件。聊天内容将简单地存储在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);
    }
}

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

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));
    }
  };
}

2 个答案:

答案 0 :(得分:1)

你应该绑定这个包含 try &的功能。 捕获。最佳做法是添加此绑定组件的构造函数

constructor(props) {
  super(props);
  this.myFunctoin = this.myfuction.bind(this);
}

答案 1 :(得分: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);
}

从功能中取出它将解决问题。