How to use BackHandler (react-native)?

0

I started learning about react-native very soon and created an application. In it I put a button to go back from the scene that works normally, but when I try to use the back button of the mobile the application is closed.

I have found that I have to use the BackHandler command to make the cell button back to the scene as well, but so far I have not found a code example that tells me exactly which parts should be adapted for each code and which ones should be kept

This is the code example I found:

return (
        componentDidMount() {
        BackHandler.addEventListener('backPress', () => {
            const { dispatch, nav } = this.props
            if (shouldCloseApp(nav)) 
                return false
            dispatch({ type: 'Back' })
                return true
        })
    }

componentWillUnmount() {
      BackHandler.removeEventListener('backPress')
    }

But when I tried to put it to run it gave the error "Unespected toekn" in the command line "componentDidMount () {".

What do I have to do?

    
asked by anonymous 17.06.2017 / 03:59

1 answer

1

I believe the error is in the place where you overwritten the componentWillMount () and componentWillUnmount ()

The correct structure should be something like:

import React, { Component } from 'react';
import { View, BackHandler } from 'react-native';

class MyScreen extends Component {

  constructor(props){
    super(props);
  }

  componentDidMount() {
    BackHandler.addEventListener('backPress', () => {
      const { dispatch, nav } = this.props;
      if (shouldCloseApp(nav)) 
        return false;
      dispatch({ type: 'Back' });
      return true;
    });
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('backPress')
  }

  render(){
    return(
      <View> {...} </View>
    )
  }
}
    
17.06.2017 / 04:36