导航后不调用`componentDidMount()`函数

hit*_*ttt 13 android reactjs react-native stack-navigator

stackNavigator用于在屏幕之间导航.我componentDidMount()在第二个活动中正在调用两个API .当我第一次加载它时,它会成功加载.然后我按回按钮返回第一个活动.然后,如果我再次进行第二次活动,则不会调用API,我会收到渲染错误.我无法找到任何解决方案.任何建议,将不胜感激.

Jit*_* Kt 30

如果有人在2018年来到这里,试试这个:

import {NavigationEvents} from 'react-navigation';
Run Code Online (Sandbox Code Playgroud)

将组件添加到渲染中:

<NavigationEvents onDidFocus={() => console.log('I am triggered')} />
Run Code Online (Sandbox Code Playgroud)

现在,每次页面聚焦时都会触发此onDidFocus事件,尽管来自goBack()或导航.

  • 没有人在 onDidFocus 和 onWillFocus 上为我工作。我正在使用 createDrawerNavigator。 (3认同)

vit*_*iso 17

如果使用 NavigationEvents 组件的 upvoted 语法不起作用,您可以尝试以下操作:

// no need to import anything more

// define a separate function to get triggered on focus
onFocusFunction = () => {
  // do some stuff on every screen focus
}

// add a focus listener onDidMount
async componentDidMount () {
  this.focusListener = this.props.navigation.addListener('didFocus', () => {
    this.onFocusFunction()
  })
}

// and don't forget to remove the listener
componentWillUnmount () {
  this.focusListener.remove()
}
Run Code Online (Sandbox Code Playgroud)


Kru*_*pös 6

React-navigation 文档明确描述了这种情况

考虑一个带有屏幕 A 和 B 的堆栈导航器。导航到 A 后,它的 componentDidMount 被调用。当推送 B 时,它的 componentDidMount 也被调用,但 A 仍然挂载在堆栈上,因此不会调用它的 componentWillUnmount。

从 B 返回到 A 时,会调用 B 的 componentWillUnmount,但 A 的 componentDidMount 不是因为 A 一直处于挂载状态。

现在有3个解决方案:

订阅生命周期事件

...

React Navigation 向订阅它们的屏幕组件发出事件。有四种不同的事件,你可以订阅: willFocuswillBlurdidFocusdidBlur。在 API 参考中阅读更多关于它们的信息。

您的许多用例可能会被withNavigationFocus 高阶组件、<NavigationEvents />组件或 useFocusState钩子覆盖。

  1. withNavigationFocus 高阶分量
  2. <NavigationEvents /> 组件
  3. 所述useFocusState钩弃用

withNavigationFocus 高阶分量

import React from 'react';
import { Text } from 'react-native';
import { withNavigationFocus } from 'react-navigation';

class FocusStateLabel extends React.Component {
  render() {
    return <Text>{this.props.isFocused ? 'Focused' : 'Not focused'}</Text>;
  }
}

// withNavigationFocus returns a component that wraps FocusStateLabel and passes
// in the navigation prop
export default withNavigationFocus(FocusStateLabel);
Run Code Online (Sandbox Code Playgroud)

<NavigationEvents /> 成分

import React from 'react';
import { View } from 'react-native';
import { NavigationEvents } from 'react-navigation';

const MyScreen = () => (
  <View>
    <NavigationEvents
      onWillFocus={payload => console.log('will focus', payload)}
      onDidFocus={payload => console.log('did focus', payload)}
      onWillBlur={payload => console.log('will blur', payload)}
      onDidBlur={payload => console.log('did blur', payload)}
    />
    {/*
      Your view code
    */}
  </View>
);

export default MyScreen;
Run Code Online (Sandbox Code Playgroud)

使用FocusState 钩子

首先安装库 yarn add react-navigation-hooks

import { useNavigation, useNavigationParam, ... } from 'react-navigation-hooks'

function MyScreen() {   const focusState = useFocusState();   return <Text>{focusState.isFocused ? 'Focused' : 'Not Focused'}</Text>; }
Run Code Online (Sandbox Code Playgroud)

这是我个人的解决方案,仅在从您的 API 获取数据时使用onDidFocus()onWillFocus()呈现:

import React, { PureComponent } from "react";
import { View } from "react-native";
import { NavigationEvents } from "react-navigation";

class MyScreen extends PureComponent {
  state = {
    loading: true
  };

  componentDidMount() {
    this._doApiCall();
  }

  _doApiCall = () => {
    myApiCall().then(() => {
      /* Do whatever you need */
    }).finally(() => this.setState({loading: false}));
  };

  render() {
    return (
      <View>
        <NavigationEvents 
              onDidFocus={this._doApiCall} 
              onWillFocus={() => this.setState({loading: true})}
        />
        {!this.state.loading && /*
        Your view code
        */}
      </View>
    );
  }
}

export default MyScreen;
Run Code Online (Sandbox Code Playgroud)


wil*_*msi 5

2020 年解决方案 / React Navigation v5

在屏幕的 ComponentDidMount 内部

componentDidMount() {
    this.props.navigation.addListener('focus', () => {
      console.log('Screen.js focused')
    });
}
Run Code Online (Sandbox Code Playgroud)

https://reactnavigation.org/docs/navigation-events/

或者:将 addListener 方法放在构造函数中以防止重复调用