【问题标题】:componentDidMount not being called after goBack navigation callgoBack 导航调用后未调用 componentDidMount
【发布时间】:2018-12-09 20:36:00
【问题描述】:

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

返回功能

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

导航功能到新屏幕

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

编辑: 嗨,我仍然坚持这个问题,想知道 SO 社区是否有解决方案来强制在调用 Navigation.goBack() 之后调用 componentDidMount,或者更确切地说如何在 this.props.navigation.navigate 之后卸载组件叫

【问题讨论】:

  • 你是如何渲染你的组件的?可能是你的其他组件在导航发生变化时并没有真正卸载,因此返回时不会再次调用componentDidMount
  • 导航到新界面后,componentDidMount会第一次被调用,返回上一屏后不再调用。导航到新屏幕后如何强制卸载屏幕?

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


【解决方案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();
    }
}

【讨论】:

    【解决方案2】:

    导航改变时组件不会被移除,所以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;
        }
    
        // ...
      }
    }
    

    【讨论】:

    • 对不起,我最近从 react-native router 迁移过来,我很困惑,或者不确定如何实现这种方法。 isFocused 是触发 redux 操作以获取数据或导航到新屏幕的布尔标志吗?
    • @AshRhazaly 不用担心。这只是一个示例,如果您不想使用,则不必使用isFocused。关键是 didFocuswillBlur 事件在这种情况下可以看作是 componentDidMountcomponentWillUnmount 钩子,因为在初始挂载后组件永远不会真正被挂载/卸载。
    • 你有一个工作点心,我可以看到这个实现吗?我不完全确定如何采用这种方法
    • @AshRhazaly 对不起,我自己没有真正的经验。我只知道written about it in the documentation是什么。
    猜你喜欢
    • 2018-06-09
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多