反应获取和设置状态

React fetch and setting state

我正在尝试在从休息服务检索到身份验证后将登录页面重定向到会员页面:

这是我的登录组件:

class Login extends Component {

  state = {
    credentials:{
      "username": "", 
      "password": ""
    },
    clientToken: ""
  }

  constructor(props){
    super(props);
    this.handleUsernameChange = this.handleUsernameChange.bind(this);
    this.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.handleFormSubmit = this.handleFormSubmit.bind(this);
  }

  handleUsernameChange(event){
    this.state.credentials.username = event.target.value;
  }


  handlePasswordChange(event){
    this.state.credentials.password = event.target.value;
  }

  handleFormSubmit(event){
    event.preventDefault();
    const data = JSON.stringify(this.state.credentials);

    fetch(loginFormurl, {
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      body: data,
    })
    .then(function(response){
      if(response.ok){
        console.log(response.headers.get('Authorization'));
        this.setState({clientToken: response.headers.get('Authorization')});
      }else{
        console.log(response.statusText);
      }
    })

    .catch(function(error) {
      console.log(error);
    });
  }

  render() {
    if (this.state.clientToken !== "") {
      return <Redirect to='./members' />;
    }

    return (
      <div className="App">
        <h1 className="Login-title">Login to Social Media Aggregator</h1>
        <form className="Login-box" onSubmit={this.handleFormSubmit}>
          <p>
            <label>
              Username
              <input id="username" type="text" name="username" required onChange={this.handleUsernameChange}/>
            </label>
          </p>
          <p>
            <label>
              Password
              <input id="password" type="password" name="password" autoComplete="password" required  onChange={this.handlePasswordChange}/>
            </label>
          </p>
          <p><input type="submit" value="Login"/></p>
        </form>
      </div>
    );
  }
}

export default withRouter(Login);

但是当获取函数 returns 并且我从授权 header 获取数据时,我无法调用 this.setState() 因为它抛出:

TypeError: Cannot read property 'setState' of undefined
    at index.js:47

关于如何解决这个问题有什么建议吗? 谢谢!

这是因为 this 解析为您创建的匿名函数(对象):

.then(function(response){ // you create a function/Object
  if(response.ok){
    console.log(response.headers.get('Authorization'));
    this.setState({clientToken: response.headers.get('Authorization')}); // `this` is the anonymous function not React component
  }else{
    console.log(response.statusText);
  }
})

出于同样的原因,您在构造函数中 bind 编辑了 class 个函数。

如果您可以使用箭头函数,这样 this 将使用使用箭头函数的上下文 - 这将是您的登录组件:

.then((response) => { // you create a function/Object
  if(response.ok){
    console.log(response.headers.get('Authorization'));
    this.setState({clientToken: response.headers.get('Authorization')}); // `this` is the anonymous function not React component
  }else{
    console.log(response.statusText);
  }
})