React-Navigation:每当导航到页面时调用函数

Ada*_*aro 5 javascript reactjs react-native react-navigation

我正在使用 React-Navigation 开发 React-Native 应用程序,并且我正在使用堆栈导航器。

导航到页面时如何调用函数,包括 goBack() 事件?如果我将方法放在我的构造函数中,它只会在其初始创建时触发,而不会在通过 goBack() 获得时触发。

Tho*_*lle 1

正如您所指出的,更改页面时组件永远不会卸载,因此您不能依赖构造函数,甚至不能依赖componentDidMount. 本期有很多关于这个话题的讨论。

例如,您可以监听didFocuswillBlur事件,并且仅在页面聚焦时才渲染页面。

例子

class MyPage 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() {
    const { isFocused } = this.state;

    if (!isFocused) {
      return null;
    }

    return <MyComponent />;
  }
}
Run Code Online (Sandbox Code Playgroud)