【问题标题】:onEnter/onExit method in React Native Component (react-native-router-flux)React Native 组件中的 onEnter/onExit 方法(react-native-router-flux)
【发布时间】:2017-11-30 12:40:55
【问题描述】:

所以我可以在路由器定义中的应用程序根目录中使用 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])

【问题讨论】:

    标签: javascript reactjs react-native react-native-router-flux


    【解决方案1】:

    您可以使用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"
      }
    }
    

    希望对你有帮助

    【讨论】:

    • 前提条件:withRef需要设置为true,否则getWrappedInstance()将不可用。 connect(null, null, null, { withRef: true })(Home);
    • @Xavier(根据redux doc withRef 已更改为forwardRef)我添加了一个{forwardRef:true},它仍然不起作用,Actions.refs 始终为空...有什么帮助吗??
    • @DanielB.
    • 我也一样 Actions.refs 总是空的
    【解决方案2】:

    请查看最新的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')
      }
    }
    

    【讨论】:

    【解决方案3】:

    简单使用componentWillUnmount,在arenaPage组件中。

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

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

    【讨论】:

    • 我的问题解决了,忘了这个。 componentWillUnmount 在这里也不起作用,因为在使用Actions.[key] 转换到下一个场景时组件不会被卸载
    • @NathanHorrigan 你是如何解决这个问题的?你能推荐吗?
    • @PorawatChimcherdsin 我在componentWillMount 中设置我的初始状态(用于初始渲染),然后当我离开场景时,我有一个onDestroy 函数,它返回一个将场景重置为的承诺它的初始状态。
    • @NathanHorrigan 是否会自动调用 onDestroy 函数?因为我没有得到类似的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多