首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Promise return from catch with Axios and final-form

Promise return from catch with Axios and final-form
EN

Stack Overflow用户
提问于 2019-03-16 17:27:56
回答 1查看 569关注 0票数 1

我正在使用Axios从React客户端登录api服务。名称和密码的表单由final-form处理。除了我想从onSubmit函数返回错误之外,一切都像预期的那样工作。

有两个组件:父Login,它使用logIn函数处理对API的调用;嵌套组件LoginUi,它具有表单和onSubmit函数,它通过this.props.logIn()调用父方法logIn

下面是父Login组件中的logIn方法:

代码语言:javascript
复制
class Login extends Component {
    constructor() {
        super();
        this.logIn = this.logIn.bind(this);
    }

    logIn(credentials) {
        return axios({
            method: 'post',
            url: 'http://0.0.0.0:3000/v1/login/',
            data: {
                name: credentials.name,
                password: credentials.password,
            },
        })
            .then((response) => {
                return response;
            })
            .catch((error) => {
                return error;
            });
    }

    render() {
        return <LoginUi logIn={this.logIn} {...this.props} />;
    }
}

export default Login;

下面是子LoginUi组件中的onSubmit方法:

代码语言:javascript
复制
class LoginUi extends Component {
    constructor(props) {
        super(props);
        this.onSubmit = this.onSubmit.bind(this);
    }

    onSubmit(credentials) {
        this.props
            .logIn(credentials)
            .then((result) => {
                console.log(result);
            })
            .catch((error) => {
                console.log(error);

                return { [FORM_ERROR]: 'Login Failed' };
            });
    }

    render() {
        return (
            <div className="LoginUi">
                {/* here goes the form with final-form, not included for brevity */}
            </div>
        );
    }
}

export default LoginUi;

{ [FORM_ERROR]: 'Login Failed' }负责通过final-form-更改表单-handled的状态,但它无法执行此操作。如果我在catch外部返回它,它可以工作:

代码语言:javascript
复制
onSubmit(credentials) {
    this.props
        .logIn(credentials)
        .then((result) => {
            console.log(result);
        })
        .catch((error) => {
            console.log(error);
        });
    return { [FORM_ERROR]: 'Login Failed' };
}

但这显然不是我想要的,因为[FORM_ERROR]: 'Login Failed'必须在API调用返回错误时才返回。

我很确定在这里使用promises是一个问题。如果任何人有任何想法,我将不胜感激!

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2019-03-16 17:40:01

由于您依赖于promise,因此onSubmit应该返回promise。将return添加到onSubmit,否则它将返回undefined,并且final-form无法知道axios调用是否已完成:

代码语言:javascript
复制
onSubmit(credentials) {
  return this.props
    .logIn(credentials)
    .then((result) => {
      console.log(result);
    })
    .catch((error) => {
      console.log(error);    
      return { [FORM_ERROR]: 'Login Failed' };
    });
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55195286

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档