0

当我尝试在 catch 子句中使用 this.setState 时,我正在从事件处理程序调用 mutate 函数并收到 Invariant Violation 错误。

saveToken({data}){
  let {userId, token, expires} = data.login;
  storeLoginToken(userId, token, expires);
  history.push('/dogs');
}
setErrors(error){
  this.setState('error', error.graphQLErrors);
}
handleSubmit(event) {
  event.preventDefault();
  let {email, password} = this.state;
  let {history} = this.props;
  let clientKey = getClientKey();
  this.props.mutate({ variables: { email, password, clientKey } })
    .then(this.saveToken.bind(this))
    .catch(this.setErrors.bind(this))
}
4

1 回答 1

0

我认为问题在于您错过了setState函数内的左括号和右括号。

我会这样写:

class ClassName extends React.Component {
  constructor(props) {
      super(props);

      this.state = {
        error,
        ...
      };
      
      this.saveToken = this.saveToken.bind(this);
      this.setErrors = this.setErrors.bind(this)
    }

    ...

    setErrors(error) {
      this.setState({error: error.graphQLErrors}); // should work with brackets
    }
    
  handleSubmit(event) {
    event.preventDefault();
    let { email, password } = this.state;
    let { history } = this.props;
    let clientKey = getClientKey();
    this.props.mutate({
        variables: {
          email,
          password,
          clientKey
        }
      })
      .then(this.saveToken)
      .catch(this.setErrors)
  }

}

于 2017-03-25T16:16:33.823 回答