简体   繁体   中英

react native call setState within componentDidUpdate error

I've a multiscreen app using react-navigation and passing a prop from CameraScreen to HomeScreen called 'barcode' like so:

takePicture() {
        //Redirect 
        this.props.navigation.navigate('Home', {barcode: true});
    }

Source: https://reactnavigation.org/docs/en/params.html

On home screen I'm listening for the prop update within componentDidMount and if barcode is true, setState to render a new component like so:

 componentDidUpdate(){
    if(this.props.navigation.getParam('barcode') === true) {
      this.setState({
        barcodeActive: true
      })
    }
  }

I get the error Invariant Violation: Maximum update depth exceeded - from calling setState within componentDidMount. I understand it's in an infinite loop with no break.

How can I listen for when this prop is passed to setState or is there a better way to achieve what I'm after?

You can use prevProps argument, and then compare current and previous values of barcode . If they are not the same, then you can update your state.

 componentDidUpdate(prevProps){
    if(this.props.navigation.getParam('barcode') !== prevProps.navigation.getParam('barcode')) {

      if( this.props.navigation.getParam('barcode')) {
        this.setState({
          barcodeActive: true
        })
       }

    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM