【问题标题】:How can I print state in the console with React Native?如何使用 React Native 在控制台中打印状态?
【发布时间】:2018-07-08 02:27:41
【问题描述】:

我正在尝试在控制台中打印状态以进行调试,但我收到以下错误消息:

无法读取未定义的属性“宠物名”

在控制台中打印状态的正确方法是什么?为什么将其称为属性?

export default class App extends Component<{}> {
  constructor(props) {
    super(props)

    this.state = {
      petname: '',
      owner: ''
    };
  }

  addPet() {
    console.log("Button Pressed");
    console.log(this.state.petname);
    return (
      //some logic
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.inputStyle}>
          <Text>Pet</Text>
          <TextInput onChangeText={petname =>                                 this.setState({petname})} style={{width:100}} />
        </View>
        <View style={styles.inputStyle} >
          <Button title="Add Pet" onPress={this.addPet} />
        </View>
      </View>
    )
  }
}

【问题讨论】:

    标签: react-native


    【解决方案1】:

    this 在您的函数中无法访问。您可以将thisonPress 上的函数绑定,也可以在构造函数中编写以下内容。

    this.addPet = this.addPet.bind(this);
    

    比较第一个和第二个选项,第二个选项更好,因为它不会每次都创建一个新实例。

    最好的选择是使用箭头功能(ES6 功能)。请考虑以下示例。

    addPet = () => {
      // Your awesome logic goes here
    }
    

    【讨论】:

    • 工作但我有更多疑问为什么要绑定 addPet 函数?这背后的动机是什么?
    • 绑定 this 是 ES5 解决方案,现在我们有箭头函数 (ES6)。你可以阅读讨论here about this topic
    【解决方案2】:

    这段代码应该可以工作:

    <Button title="Add Pet" onPress={this.addPet.bind(this)} />
    

    【讨论】:

      【解决方案3】:

      把函数改写成这样:

      addPet = () => {
          console.log("Button Pressed");
          console.log(this.state.petname);
          return (
              // Some logic
          );
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-02
        • 1970-01-01
        • 2016-07-31
        • 2018-05-16
        • 1970-01-01
        • 2013-01-21
        • 2014-01-28
        相关资源
        最近更新 更多