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

我正在尝试通过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')
评论
  • 如果他
    如果他 回复

    删除此行:

    constructor(props) {
        super(props)
      }
    
  • 兔小乖
    兔小乖 回复

    您需要按以下方式绑定功能

    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>
            );
        };
    }