react.js无法读取未定义的属性'setState'

时间:2019-08-26 14:30:10

标签: javascript json reactjs xmlhttprequest setstate

这是我的Profile课:

class Profile extends React.Component {
state={email:'',userName:'',userID:''};
getData()
{
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            {
            console.log(this.responseText);
            this.setState({'userID':JSON.parse(this.responseText).userID});
            console.log(this.responseText);
          Profile.this.setState({userID:JSON.parse(this.responseText).userID});
        }
    };
    request.open('GET', 'http://localhost:8080/user/1');
    request.send();
}
componentWillMount() {
    this.getData()
}
render() {
    return(
<div>
     {this.props.userID}
</div>
    );
}
}
 export default Profile;

这给了我一个错误,说无法读取未定义的属性'setState'

错误:

Profile.this.setState({userID:JSON.parse(this.responseText).userID});

这是怎么了?如何解决?

3 个答案:

答案 0 :(得分:1)

没有interfaceProfile.this是一个类,您必须保留对该实例的引用或使用箭头函数而不是普通函数,这里最简单的方法是保留对组件的引用,这是一个示例:

Profile

答案 1 :(得分:1)

您有很多错误,这是正确的方法

class Profile extends React.Component {
  constructor(props) {
    super(props);
    // You need to set the initial state inside the constructor
    this.state = { email: "", userName: "", userID: "" };
  }
  getData() {
    // use let instead of var
    let request = new XMLHttpRequest();
    // call request.open outside of the handler
    request.open("GET", "http://localhost:8080/user/1");
    // use an arrow function so that you will have access to the class this context
    request.onreadystatechange = () => {
      // you must directly reference request, not this
      if (request.readyState === 4 && request.status === 200) {
        const { userID } = JSON.parse(request.responseText);
        // destruct instead of typing the entire thing
        // use the shorthand way of creating object with same name properties
        this.setState({ userID });
      }
    };
    // call request.send outside of the handler
    request.send();
  }
  // use componentDidMount , componentWillMount is deprecated
  componentDidMount() {
    this.getData();
  }
  render() {
    // you should get the userID from the this.state not this.props
    return <div>{this.state.userID}</div>;
  }
}

答案 2 :(得分:-1)

尝试

您有多个引用不同事物的上下文。

public partial class NewProductsMenu : ThemedWindow
{
    public NewProductsMenu()
    {
        InitializeComponent();
        DataContext = NewProductsMenuVM.Instance;
    }

    ...
    public void saveToDB()
    {
        string ProductName = NewProductsMenuVM.Instance.ProductName;
    }
}