ReferenceError:状态未定义-反应本机

时间:2020-02-10 10:18:12

标签: reactjs react-native expo

在练习时我没有得到错误状态的定义,因为我检查文档是否使用相同格式创建状态

function App() {

  // build state
  state = {
    Name:'Hamza',
    Status: 'Comitted'
  };
  // function
  ChangeProfile=()=>{
    this.setState({
      Name: 'Shahwar'
    });
    this.setState({
      Status: 'Divorced'
    });
    console.log('updated',this.state);
  }
  return (
    <View style={styles.container}>
      <Text>{this.state.Name}</Text>
      <Text>{this.state.Status}</Text>
      <Button title="Click Me!" onPress={this.ChangeProfile} />
    </View>
  );
}

export default App;

3 个答案:

答案 0 :(得分:1)

您正在尝试混合基于类和基于功能的类。您的代码应该像这样。

ele

答案 1 :(得分:1)

您必须使用Class组件才能使用状态。

class App extend React.Component
 {
   constructor(props) {
   super(props);
     this.state={
       // enter code here
      }
 }

render(){
return(
//enter code here
  )
  }
}

答案 2 :(得分:0)

根据此代码。您应该得到解析错误。它应该具有render()方法。

render() {
    return (
        <View style={styles.container}>
            <Text>{this.state.Name}</Text>
            <Text>{this.state.Status}</Text>
            <Button title="Click Me!" onPress={this.ChangeProfile} />
        </View>
    );
}
相关问题