Navigation between Screens but constructor is not calling

ε祈祈猫儿з 提交于 2020-06-17 15:16:31

问题


I have multiple screens in my app, I used CreatStackNavigator for navigation. If I visit the screen second time the constructor is not getting called.

Let suppose I have four screen A,B,C & D and currently I am at A.

Then I go to C and then D screens respectively.

Now if I clicked on C again then the constructor of C is not getting called.

I used ComponentReceivedMount() also but it didn't worked.

My code is :-

  constructor(props) {
    super(props);
    ToastAndroid.show('heeeelll', ToastAndroid.LONG);
    this.state = {
        drawerOpen: false,
        op: 1,
        cl: '#ffffff',
        swiper: this.renderSwpier,
        showSwiper: false,
        ftc: '#2c3554',
        stc: '#c8c8c8',
        firstTopcolor: 1,
        secondTopColor: 0,
        showview: true,
    }
}

Thank you in advance.


回答1:


React navigation has its own navigation lifecycle api available, which allows you to determine when a screen has become active.

For more information check the docs: https://reactnavigation.org/docs/en/navigation-lifecycle.html

The withNavigationFocus HOC provides an isFocused prop which allows you to determine is a screen is visible.

Example:

import { withNavigationFocus } from 'react-navigation';

class YourScreen extends React.Component {

  render() {
     ...
  }

  componentDidUpdate(prevProps) {
    if (this.props.isFocused && !prevProps.isFocused) {
      // Screen has now come into focus, perform your tasks here! 
    }
  }

}

export default withNavigationFocus(YourScreen)



回答2:


Calling C second time will not call constructor because C is already mounted before as u called it from A and constructor is invoked when a new instance of a class is generated. You can use componentwillmount() and componentdidmount() in place of relying on constructor.



来源:https://stackoverflow.com/questions/54039505/navigation-between-screens-but-constructor-is-not-calling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!