Search code examples
react-nativereact-navigationreact-navigation-drawer

Constructor of Component is not working for the second time


I have a Component class:

class AutoPage extends Component {
constructor(props) {
    super(props);
    console.log("Auto is " + this.props.route.params.auto);
    this.state = {
        avto: this.props.route.params.auto,
    }
    this.array = [
        this.state.avto.PICTURE,
    ];

    for (let dopImage of this.state.avto.DOP_FOTO.VALUE) {
        this.array.push(dopImage);
        //console.log(avto);
    }
    }
}

I am opening this Component from another place:

<TouchableOpacity onPress={() => navigate('AutoPage', {
                auto: item
              })}>

Here is my drawer navigation:

 <Drawer.Navigator drawerContent={props => <CustomSidebarMenu {...props} />} width={Dimensions.get('window').width - 130}
  component={CustomSidebarMenu}>
  <Stack.Screen name="AutoListPage" component={AvtoListPageNav} />
  <Stack.Screen name="AutoPage" component={AutoPage} options={{ headerTitle: "GorodAvtoPrime", headerTitleAlign: "center" }} /> 
</Drawer.Navigator>

When I click TouchableOpacity AutoPage opens and its constructor works. But when go back and click TouchableOpacity again, AutoPage opens and its constructor doesn't work. And I am getting previous data in this.props.route.params.auto. How can I make run constructor of AutoPage every time when I click TouchableOpacity?


Solution

  • You'll probably want to subscribe to the focus navigation event. The screen is being reused so it isn't created again.

    https://reactnavigation.org/docs/navigation-events

    class AutoPage extends Component {
      constructor(props) {
        super(props);
        this.state = {
            avto: null,
        }
      }
    
      componentDidMount() {
        this._unsubscribe = this.props.navigation.addListener('focus', () => {
          // Update your state here
        });
      }
    
      componentWillUnmount() {
        this._unsubscribe();
      }
    }