【问题标题】:Invariant Violation setting state in Apollo mutate callbackApollo mutate 回调中的不变违规设置状态
【发布时间】:2017-08-18 02:40:47
【问题描述】:

当我尝试在 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))
}

【问题讨论】:

    标签: reactjs react-apollo


    【解决方案1】:

    我认为问题在于您错过了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)
      }
    
    }

    【讨论】:

      猜你喜欢
      • 2022-10-18
      • 1970-01-01
      • 2021-02-13
      • 2018-10-05
      • 2018-10-29
      • 2020-08-27
      • 2018-10-30
      • 2020-05-06
      • 2020-11-25
      相关资源
      最近更新 更多