在Mutation中出现错误时显示SnackBar Material UI

时间:2019-02-10 11:56:28

标签: reactjs material-ui apollo mutation snackbar

我使用Materia-UI页上的小吃店(第一个示例-自定义的SnackBars)

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);

在该示例中,单击“ OPEN SUCCESS SNACKBAR”按钮时显示小吃店

我想在表格上的“阿波罗的突变”出现错误时显示错误的小吃店。

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

问题是我不知道如何触发on Error函数显示SnackBar。如何更改小吃店的状态?我正在尝试使用here的解决方案,但收到一条错误消息

  

openSnackbarFn不是函数

谢谢。

1 个答案:

答案 0 :(得分:2)

从根本上说,您希望Snackbar成为Mutation的同级产品,并让其共同的父对象(即您的组件)处理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>
  )
}