开发者问题收集

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

2020-04-24
759

我正尝试通过 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个回答

您需要按如下方式绑定您的功能

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>
        );
    };
}
Rajan
2020-04-24

删除此行:

constructor(props) {
    super(props)
  }
brandoncraig
2020-04-24