goBack导航调用后未调用componentDidMount

时间:2018-07-01 09:50:58

标签: javascript reactjs react-native react-redux react-navigation

我已经设置了一个StackNavigator,它将导航到另一个屏幕并返回上一个屏幕之后,将执行redux操作以在componentDidMount上获取数据,componentDidMount不再触发,我呈现白色屏幕。我尝试使用StackActions.reset重置StackNavigator,但这只会导致我的其他屏幕无法正常安装,从而呈现空白屏幕。是否有办法在componentDidMount之后强制this.props.navigation.goBack()

返回功能

_goBack = () => {
  this.props.navigation.goBack();
};

导航到新屏幕的功能

_showQuest = (questId, questTitle ) => {
  this.props.navigation.navigate("Quest", {
    questId,
    questTitle,
  });
};

编辑: 嗨,我仍然对此事保持关注,并想知道SO社区是否有一种解决方案来强制在调用Navigation.goBack()之后调用componentDidMount,或者更确切地说,如何在this.props.navigation.navigate之后卸载组件。叫

2 个答案:

答案 0 :(得分:4)

导航更改时不会删除这些组件,因此componentDidMount仅在第一次呈现时被调用。

您可以改用this alternative approach

class MyComponent extends React.Component {
  state = {
    isFocused: false
  };

  componentDidMount() {
    this.subs = [
      this.props.navigation.addListener("didFocus", () => this.setState({ isFocused: true })),
      this.props.navigation.addListener("willBlur", () => this.setState({ isFocused: false }))
    ];
  }

  componentWillUnmount() {
    this.subs.forEach(sub => sub.remove());
  }

  render() {
    if (!this.state.isFocused) {
      return null;
    }

    // ...
  }
}

答案 1 :(得分:1)

didFocus事件监听器不适用于我。

我找到了另一个名为focus的监听器,它终于起作用了!

componentDidMount() {
    const { navigation } = this.props;
    
    this.focusListener = navigation.addListener('focus', () => {
        // call your refresh method here
    });
}

componentWillUnmount() {
    // Remove the event listener
    if (this.focusListener != null && this.focusListener.remove) {
        this.focusListener.remove();
    }
}