来自BackHandler的React Native setState无法按预期工作

时间:2020-04-24 12:21:41

标签: javascript reactjs react-native

我正在尝试通过BackHandler函数(按下后退按钮)更新App类的状态。难道我做错了什么? 这是我的App.js

export default class App extends React.Component {
  constructor(props) {
    super(props)
    this._changeDisplayOpt = this._changeDisplayOpt.bind(this)
  }

  state = {
    screen: "room",
  }

  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
  }

  handleBackButton() {
    if(this.state.screen == "room"){
      this.setState({screen:'home'});
    }
    return true;
  }

  render(){
    return(
      <View style={styles.container}>
         <Text>{this.state.screen}</Text>
      </View>
    );
  };
}

它给了我这个错误

TypeError: undefined is not an object (evaluating 'this.state.screen')

2 个答案:

答案 0 :(得分:2)

您需要按如下所示绑定功能

export default class App extends React.Component {
    constructor(props) {
        super(props)
        this.handleBackButton = this.handleBackButton.bind(this);
    }

    state = {
        screen: "room",
    }

    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
    }

    handleBackButton() {
        if (this.state.screen == "room") {
            this.setState({ screen: 'home' });
        }
        return true;
    }

    render() {
        return (
            <View style={styles.container}>
                <Text>{this.state.screen}</Text>
            </View>
        );
    };
}

答案 1 :(得分:0)

删除此行:

constructor(props) {
    super(props)
  }