首页 > 解决方案 > goBack 导航调用后未调用 componentDidMount

问题描述

我已经设置了一个 StackNavigator,它将触发一个 redux 操作来获取数据componentDidMount,在导航到另一个屏幕并返回到前一个屏幕之后,componentDidMount它不再触发并且我看到一个白屏。我尝试使用重置 StackNavigator ,StackActions.reset但这只会导致我的其他屏幕也无法安装,进而显示一个空屏幕。有没有办法强制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 之后卸载组件。导航被称为

标签: javascriptreactjsreact-nativereact-reduxreact-navigation

解决方案


导航更改时不会删除组件,因此componentDidMount只会在第一次渲染时调用。

您可以改用这种替代方法

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

    // ...
  }
}

推荐阅读