一旦字段在Formikl/Yup中有效,如何执行自定义功能 [英] How to execute custom function once the field is valid with Formikl / Yup

查看:198
本文介绍了一旦字段在Formikl/Yup中有效,如何执行自定义功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在字段变为有效时执行自定义功能吗?

I want execute a custom function when the field become valid?

类似这样的事情..
<Field name="postal-code" onValid={...} />

Something like this..
<Field name="postal-code" onValid={...} />

原因是,一旦用户输入有效的邮政编码,我想让获取(GET)从API获取地址

The reason is that I want make fetch (GET) to get address from API once the user type an valid Postal code

推荐答案

您可以这样解决:

  • 具有Loader组件,该组件会在获取URL时加载数据
  • 如果touched[fieldName] && !errors[fieldName]
  • ,则将URL传递给该组件
  • have Loader component which loads data if it gets an URL
  • pass URL to this component if touched[fieldName] && !errors[fieldName]

Loader组件可以像

import { PureComponent } from 'react';
import PropTypes from 'prop-types';
import superagent from 'superagent'; // swap to your xhr library of choice

class Loader extends PureComponent {
  static propTypes = {
    url: PropTypes.string,
    onLoad: PropTypes.func,
    onError: PropTypes.func
  }

  static defaultProps = {
    url: '',
    onLoad: _ => {},
    onError: err => console.log(err)
  }

  state = {
    loading: false,
    data: null
  }

  componentDidMount() {
    this._isMounted = true;
    if (this.props.url) {
      this.getData()
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.url !== this.props.url) {
      this.getData(nextProps)
    }
  }

  componentWillUnmount() {
    this._isMounted = false
  }

  getData = (props = this.props) => {
    const { url, onLoad, onError } = props;

    if (!url) {
      return
    }

    this.setState({ data: null, loading: true });

    const request = this.currentRequest = superagent.
      get(url).
      then(({ body: data }) => {
        if (this._isMounted && request === this.currentRequest) {
          this.setState({ data, loading: false }, _ => onLoad({ data }));
        }
      }).
      catch(err => {
        if (this._isMounted && request === this.currentRequest) {
          this.setState({ loading: false });
        }
        onError(err);
      });
  }

  render() {
    const { children } = this.props;
    return children instanceof Function ?
      children(this.state) :
      children || null;
  }
}

如果未传递url,则不执行任何操作.网址更改时-会加载数据.

If no url is passed, it does nothing. When url changes - it loads data.

Formik渲染/儿童道具中的用法:

Usage in Formik render/children prop:

<Loader
  {...(touched[fieldName] && !errors[fieldName] && { url: URL_TO_FETCH })}
  onLoad={data => ...save data somewhere, etc.}
/>

这篇关于一旦字段在Formikl/Yup中有效,如何执行自定义功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆