1

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

这是我的登录组件:

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);

但是当 fetch 函数返回并且我从 Authorization 标头获取数据时,我不能调用 this.setState() 因为它抛出:

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

关于如何解决这个问题的任何建议?谢谢!

4

1 回答 1

2

这是因为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在构造函数中拥有 ed 类函数。

如果您可以使用箭头功能,这种方式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);
  }
})
于 2018-04-27T17:28:51.233 回答