在goBack导航调用之后没有调用componentDidMount

问题描述 投票:5回答:1

我已经设置了一个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之后卸载组件。导航被称为

javascript reactjs react-native react-redux react-navigation
1个回答
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;
    }

    // ...
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.