React Native 组件中的 onEnter/onExit 方法(react-native-router-flux)

IT技术 javascript reactjs react-native react-native-router-flux
2021-05-19 21:34:00

所以我可以在路由器定义中我的应用程序的根目录中使用 onEnter/onExit 方法,它工作得非常好:

<Scene key="arena" hideNavBar={true}  onEnter={() => console.log("Entered")} component={ArenaPage} />

有什么方法可以在组件本身内部执行此操作,以便我可以更新本地状态?

export default class ArenaPage extends Component {
    onEnter () {
        this.setState(...)
    }
    // Render blah blah blah...
}

如果不可能,是否有在离开场景时触发 componentWillUnmount (Actions.[key])

3个回答

您可以使用onEnteronExit方法来获得您想要的结果。反过来可以this像这样访问

import { Actions } from 'react-native-router-flux'

class Home extends Component {
  static onEnter() {
     // homeSceneKey needs to be the same key that you use to configure the Scene
     Actions.refs.homeSceneKey.getWrappedInstance().myFunction()
  };

  myFunction = () => {
     // have access to this (props and state) here
     this.blah = "what ever you want to do"
  }
}

希望这可以帮助

请检查 latest react-native-router-flux:beta.27,现在您可以将 onEnter、onExit 方法定义为您的react组件方法。

class Home extends Component {
  static onEnter() {
    console.log('On Focus Enter')
  };
  static onExit() {
    console.log('On Focus Exit')
  }
}

在 arenaPage 组件中简单使用 componentWillUnmount。

componentWillUnmount() {
    // add your code here.
}

因为这将在导航离开组件时运行。我正在使用它来删除错误消息。这有效。