Как выполнить пользовательскую функцию, если поле действительно с Formikl / Yup - PullRequest
0 голосов
/ 31 августа 2018

Я хочу выполнить пользовательскую функцию, когда поле станет действительным?

Как то так ..
<Field name="postal-code" onValid={...} />

Причина в том, что я хочу, чтобы make fetch (GET) получал адрес из API, как только пользователь введет действительный почтовый код

Ответы [ 2 ]

0 голосов
/ 03 сентября 2018

Вы можете решить это так:

  • имеет Loader компонент, который загружает данные, если получает URL
  • передать URL этому компоненту, если 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 не передан, он ничего не делает. При изменении URL-адреса загружаются данные.

Использование в Formik render / children prop:

<Loader
  {...(touched[fieldName] && !errors[fieldName] && { url: URL_TO_FETCH })}
  onLoad={data => ...save data somewhere, etc.}
/>
0 голосов
/ 31 августа 2018

Вы можете определить пользовательскую функцию внутри класса компонента или вне компонента.

// outside the component (best suited for functional component)
const onValidFn = () => {
 // perform action
}
// inside the component (best suited for stateful component)
onValidFn() {
 // perform action
}

Если вы хотите получить доступ к this внутри метода onValidFn, вы можете связать this внутри конструктора или использовать метод открытого класса :

onValidFn = () => {
  // perform action
  console.log(this)
}

// if your method is defined in outer scope
<Field name="postal-code" onValid={onValidFn} />

// if your method is defined in inner scope (inside class)
<Field name="postal-code" onValid={this.onValidFn} />
...