0

I have this parent snippet of code:

render(){
    return (
      <NavigationContainer>
        <Stack.Navigator initialRouteName="Home">
          <Stack.Screen name="Home" >
            {(props) => <HomeScreen {...props} scannedURL={this.state.scannedURL}/>}
          </Stack.Screen>
          <Stack.Screen name="Scan">
            {(props) => <ScanScreen {...props} scanSuccess={this.scanSuccess}/>}
          </Stack.Screen>
        </Stack.Navigator>
      </NavigationContainer>
    );
  }

when I update the state, this render method succesfully runs again, but my , which uses the parent state, does not re-render. Does anyone have any idea why? Is this a Navigator specific issue?

In HomeScreen I also have this:

this.state = {
    scannedURL: props.scannedURL,
}

EDIT: interestingly, in my HomeScreen component, whereI used this.state.scannedURL, I replaced with this.props.scannedURL and it worked? Is the constructor not running again? Im kinda lost

microflakes
  • 313
  • 2
  • 10
  • At initializing the `HomeScreen` you assign the local state `scannedURL ` to what has been passed with props. But on props change do you update local state? React does not construct everything again, just re-render on a state or prop change according to usage. – Amir-Mousavi May 27 '20 at 18:00
  • The constructor only gets called once when a component mounts. After that, a component re-renders (which does not call the constructor). Also an important note: its an anti-pattern to simply mirror props into state. Its ok if you use props to initialize the state, but unless the state value is going to change after the initialization it should not be in state. Instead (like you've discovered) use the prop directly. – Brian Thompson May 27 '20 at 18:05
  • Oh cool thanks! I didn't know it wasn't common practice to mirror props to state. Not sure why but seemed like it was worse practice to be referencing props everywhere. state seemed to be cleaner. Not sure why I thought that. Could you explain more on why its anti-react to mirror props to state? – microflakes May 27 '20 at 19:10
  • relevant for anyone viewing this issue; https://stackoverflow.com/questions/41233458/react-child-component-not-updating-after-parent-state-change – microflakes May 27 '20 at 19:11
  • [This section of the docs](https://reactjs.org/docs/thinking-in-react.html#step-3-identify-the-minimal-but-complete-representation-of-ui-state) gives a list of questions to ask to determine what should and should not be a part of state. Its part of a larger example, but the three questions are universal – Brian Thompson May 27 '20 at 21:05

0 Answers0