reactjs - 方法无法读取状态

标签 reactjs react-native parse-server

我正在使用react-native和解析服务器。我正在实现用户注册,但出现此错误:

undefined is not object (evaluating 'this.state.username')

不应该在全类范围内读取状态吗?

import React, {Component} from 'react';
import {Container, Content, Form, Item, Input, Button, Text} from 'native-base';
var Parse = require('parse/react-native');

export default class Singup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: ''
    };
  }

  Buttonpress() {
    Parse.initialize("APPLICATION_ID");
    Parse.serverURL = 'http://***.***.**.**:1337/parse'

    var user = new Parse.User();
    user.set("username", this.state.username);
    user.set("password", this.state.password);

    user.signUp(null, {
      success: function(user) {
        console.warn("YES");
      },
      error: function(user, error) {
        // Show the error message somewhere and let the user try again.
        alert("Error: " + error.code + " " + error.message);
      }
    });
  }

  render() {
    return (
      <Container>
        <Content>
          <Form>
            <Item>
              <Input
                placeholder="Username"
                onChangeText={(text) => this.setState({username: text})}
                value = {this.state.username}/>
            </Item>
            <Item last>
              <Input
                placeholder="Password"
                onChangeText={(text) => this.setState({password: text})}
                value = {this.state.password}/>
            </Item>
          </Form>
          <Button
            block
            onPress={this.Buttonpress}>
            <Text>Inscrever-se</Text>
          </Button>
        </Content>
      </Container>
    );
  }
}

自动翻译。

最佳答案

绑定(bind)你的函数应该对你有帮助

  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: ''
    };
    this.Buttonpress = this.Buttonpress.bind(this);
  }

这是引用:https://facebook.github.io/react/docs/react-without-es6.html#autobinding

关于reactjs - 方法无法读取状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45242888/

相关文章:

reactjs - React TypeScript : Types of property 'X' are incompatible. 类型 'Y' 不可分配给类型 'Z'

ios - 解析服务器云代码查询语法错误141

javascript - Mobx @observer 组件是否触发 `render` 或 `forceUpdate` ?

reactjs - React-bootstrap 以编程方式更改事件选项卡

node.js - 即使关闭终端后,如何为reactjs运行npm start?

javascript - 将 StackNavigator 嵌套在 BottomTabNavigator 中 React-navigator v5

javascript - 使用属性名称更新对象属性中的数组

react-native:未在 Mac OS Big Sur 上设置 ANDROID_HOME 变量

ios - PFObject 值可能没有类 : _SwiftValue

ios - 如何防止其他开发者破坏我们的 Parse 服务器数据