【问题标题】:React Native - navigation.addListner is not an objectReact Native - navigation.addListner 不是对象
【发布时间】:2020-03-09 01:29:36
【问题描述】:

App.js:

import React, { Component } from 'react';
import {View,Text} from 'react-native';
import { createDrawerNavigator } from 'react-navigation-drawer';
import {createAppContainer} from 'react-navigation';

import Epics from './screens/tmp';
import Pager from './screens/Pager';

const DrawerNavigator = createDrawerNavigator({
 Home: {screen: Epics},
 Page: {screen: Pager}
},{initialRouteName: 'Home'});

const Stack = createAppContainer(DrawerNavigator);

export default class App extends Component {
  render() {
    return <Stack />;
  }
}

每次用户使用导航 addListner 事件登陆屏幕时尝试调用 fetch API

componentDidMount() {
   this.loadFeed(); // fetch API
   const { navigation } = this.props;
   this.focus = navigation.addListener('willFocus', () => {
     this.loadFeed(); // fetch API
   });
}

来自 package.json 的 React Navigation 版本:

  • “反应导航”:“^4.2.2”
  • “反应导航抽屉”:“^2.4.2”

有没有更好的方法来检测应用上的活动屏幕并调用 fetch API?或者修复下面给出的错误?

类型错误:未定义不是对象(评估“navigation.addListner”): Error when the app launches

更新

我正在尝试在零食中复制以下示例:https://snack.expo.io/HkrP8YPIf

我做错了什么? (我是 React Native 新手,请帮我理解)

【问题讨论】:

    标签: android ios react-native expo react-native-navigation


    【解决方案1】:

    尝试使用 react-navigation 4.x 附带的 NavigationEvents 组件。只需将它嵌套在屏幕的渲染方法中的任何位置即可。

    例子:

    import React from 'react';
    import { View } from 'react-native';
    import { NavigationEvents } from 'react-navigation';
    
    const MyScreen = () => (
      <View>
        <NavigationEvents
          onWillFocus={() => console.log('Screen will be in focus')}
          onDidFocus={() => console.log('Screen is in focus')}
          onWillBlur={() => console.log('Screen will blur')}
          onDidBlur={() => console.log('Screen blurred')}
        />
        {/*
          other code
        */}
      </View>
    );
    
    export default MyScreen;
    

    【讨论】:

      【解决方案2】:

      这只是意味着navigation 不存在。所以看起来组件应该通过道具接收它而不是。这就是我可以从这段代码中看出的全部内容。

      【讨论】:

      • 我是 React Native 的新手,我正在努力理解这一点。在给定的零食示例中:snack.expo.io/HkrP8YPIf,this.prop 没有明确定义,但它可以工作。我做错了什么?
      • 我自己不使用“react-navigation”(我使用了一个名为“react-native-navigation”的不同包,它的工作方式略有不同)。但是,从这段代码看来,您的 App 组件只是呈现 Navigator。 Navigator 有一些特定于“react-navigation”的语法,看起来它正在包装您制作的组件(FirstScreen 和 SecondScreen)。这是它将添加道具导航的地方,然后您可以在组件本身中访问它。也许更熟悉这个包的人可以帮助你处理你的特定代码。这就是我真正能说的。
      【解决方案3】:

      检查你的道具钥匙,同意詹姆斯的观点。在这里有一个建议,因为你期待一个道具,你应该处理这个常见的错误,不管 key 是否存在(if else)

      【讨论】:

      • 我是 React Native 的新手,我正在努力理解这一点。在给定的零食示例中:snack.expo.io/HkrP8YPIf,this.prop 没有明确定义,但它可以工作。我做错了什么?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多