Search code examples
reactjsreact-nativenavigationlifecyclestack-navigator

componentWillReceiveProps not receiving props on first call react native


I have two screens on a tab bar (default react native tab bar). When I try to navigate to 'MapScreen' (the non-default screen of the tab bar), using a stack navigator while passing some additional data, the first call of the method always defaults to 'default' instead of receiving the 'region' data passed. However, when I go back to the original screen and try again, the data is passed fine. Why is 'region' not properly initialized the first time I use the stack navigation function?

Screen to open to:

moveToMapScreen = (lat: number, lon: number) => {
    this.props.navigation.navigate('MapScreen', {
      region: {
        latitude: lat,
        longitude: lon,
        latitudeDelta: 0.00001,
        longitudeDelta: 0.00001,
      },
    });
  }

MapScreen:

  componentWillReceiveProps() {
    const preRegion = this.props.navigation.getParam('region', 'default');
    if (preRegion !== 'default') {
      this.setState({
        region: preRegion,
      });
    }
  }

Solution

  • you are not passing nextProps to the componentWillReceiveProps , your code should be like below:

    componentWillReceiveProps(nextProps) {
        // use nextProps inside however you want
        const preRegion = this.props.navigation.getParam('region', 'default');
        if (preRegion !== 'default') {
          this.setState({
            region: preRegion,
          });
        }
      }