Показывать пользовательский интерфейс SnackBar Material при появлении ошибки в Mutation - PullRequest
0 голосов
/ 10 февраля 2019

Я использую Снэк-бар со страницы Materia-UI (первый пример - Индивидуальные Снэк-бары)

const variantIcon = {
  success: CheckCircleIcon,
  warning: WarningIcon,
  error: ErrorIcon,
  info: InfoIcon,
};

const styles1 = theme => ({
  success: {
    backgroundColor: green[600],
  },
  error: {
    backgroundColor: theme.palette.error.dark,
  },
  info: {
    backgroundColor: theme.palette.primary.dark,
  },
  warning: {
    backgroundColor: amber[700],
  },
  icon: {
    fontSize: 20,
  },
  iconVariant: {
    opacity: 0.9,
    marginRight: theme.spacing.unit,
  },
  message: {
    display: 'flex',
    alignItems: 'center',
  },
});

function MySnackbarContent(props) {
  const { classes, className, message, onClose, variant, ...other } = props;
  const Icon = variantIcon[variant];

  return (
    <SnackbarContent
      className={classNames(classes[variant], className)}
      aria-describedby="client-snackbar"
      message={
        <span id="client-snackbar" className={classes.message}>
          <Icon className={classNames(classes.icon, classes.iconVariant)} />
          {message}
        </span>
      }
      action={[
        <IconButton
          key="close"
          aria-label="Close"
          color="inherit"
          className={classes.close}
          onClick={onClose}
        >
          <CloseIcon className={classes.icon} />
        </IconButton>,
      ]}
      {...other}
    />
  );
}

MySnackbarContent.propTypes = {
  classes: PropTypes.object.isRequired,
  className: PropTypes.string,
  message: PropTypes.node,
  onClose: PropTypes.func,
  variant: PropTypes.oneOf(['success', 'warning', 'error', 'info']).isRequired,
};

const MySnackbarContentWrapper = withStyles(styles1)(MySnackbarContent);

const styles2 = theme => ({
  margin: {
    margin: theme.spacing.unit,
  },
});

class CustomizedSnackbar extends React.Component {
  state = {
    open: false,
  };

  handleClick = () => {
    this.setState({ open: true });
  };

  handleClose = (event, reason) => {
    if (reason === 'clickaway') {
      return;
    }
    this.setState({ open: false });
  };

  render() {
    return (
      <div>
        <Snackbar
          anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'left',
          }}
          open={this.state.open}
          autoHideDuration={2000}
          onClose={this.handleClose}
        >
          <MySnackbarContentWrapper
            onClose={this.handleClose}
            variant="error"
            message="This is an error message!"
          />
        </Snackbar>
      </div>
    );
  }
}

export default withStyles(styles2)(CustomizedSnackbar);

В примере снэк-бар отображается при нажатии на кнопку «ОТКРЫТЬ СНАК УСПЕХА УСПЕХА»"

Я хотел бы показать панель ошибок, когда Mutation от Apollo в моей форме выдает ошибку.

render(){
 return(
  <div>
   <Mutation
    mutation={this.mutationQuery}
    onError={() =>
     //here show Snack Bar
    }
    onCompleted={data => { console.log(data); }}
   >
  {mutation => (
//here is the form
)}
)}

Проблема в том, что я не знаю, как вызвать отображение SnackBar вфункция при ошибке.Как изменить состояние закусочной?Я пробовал решение из здесь , но я получаю сообщение об ошибке, что

openSnackbarFn не является функцией

Заранее спасибо.

1 Ответ

0 голосов
/ 10 февраля 2019

По сути, вы хотите, чтобы ваша Snackbar была родственным элементом вашей Мутации, и чтобы их общий родительский элемент (т.е. ваш компонент) обрабатывал состояние открытия / закрытия Snackbar.

Компонент стиля класса

class FormWithMutationAndSnackbar extends React.Component {
  state = {
    open: false
  }

  handleOpen = () => this.setState({ open: true })

  handleClose = () => this.setState({ open: false })

  render() {
    const { open } = this.state
    return(
      <React.Fragment>
        <Mutation
          mutation={this.mutationQuery}
          onError={(err) => {
            // use err to set Snackbar contents for example
            this.handleOpen()
          }
          onCompleted={data => { console.log(data); }}
        >
          {mutation => (
            //here is the form
          )}
        </Mutation>
        <Snackbar
          open={open}
          onClose={this.handleClose}
          // other Snackbar props
        >
          // Snackbar contents
        </Snackbar>
      </React.Fragment>
    )
  }
}

Функциональный компонент с крючками

const FormWithMutationAndSnackbar = () => {
  const [open, setOpen] = useState(false)

  return(
    <React.Fragment>
      <Mutation
        mutation={this.mutationQuery}
        onError={(err) => {
          // use err to set Snackbar contents for example
          setOpen(true)
        }
        onCompleted={data => { console.log(data); }}
      >
        {mutation => (
          //here is the form
        )}
      </Mutation>
      <Snackbar
        open={open}
        onClose={() => setOpen(false)}
        // other Snackbar props
      >
        // Snackbar contents       
      </Snackbar>
    </React.Fragment>
  )
}
...