使用 Material UI Web 组件在两个页面之间传递单个布尔值 useState

Passing a single boolean useState between two pages using Material UI web components

我一直在尝试在两个页面之间传递布尔值 useState,使用此处显示的最佳实践:How to call useState from another Page?

我的主要 objective 是在 "./demo"

上成功提交表单后,在不同的页面上显示成功警报

Demo.js 持有一个带有 submit button 的对话框,将 setSuccess 设置为 true。

import Alert from "./alert";

export default function AlertDialog() {
  const [success, setSuccess] = React.useState(false); // <- Hides and Shows the Alert Message

  const handleSubmit = () => {
    return (
      <Alert
        setSuccess={() => {
          setSuccess(true); // <- How I am trying to setSuccess to true.
        }}
      />
    );
  };

  return (
        <DialogActions>
          <Button
            onClick={handleSubmit}
            color="primary"
            autoFocus
            component={RouterLink}
            to={"/"}
          >
            Submit
          </Button>
        </DialogActions>
  );

Alert.js 一旦 success 设置为真,就会出现一条警告消息。

export default function Alerts(props) {
  // const [open, setOpen] = React.useState(false);
  const { success, setSuccess } = props;

  return (
    <div>
      <Collapse in={success}>
        <Alert
          action={
            <IconButton
              aria-label="close"
              color="inherit"
              size="small"
              onClick={() => {
                setSuccess(false);
              }}
            >
              <CloseIcon fontSize="inherit" />
            </IconButton>
          }
        >
          Form Successfully Submitted
        </Alert>
      </Collapse>
      <Button
        disabled={success}
        variant="outlined"
        component={RouterLink}
        to={"/demo"}
      >
        Go Back to Submit Form
      </Button>
    </div>
  )

; }

有人可以解释一下如何在提交后显示成功提示吗?如果您想深入了解,请访问此处 https://codesandbox.io/s/alert-test-qhkbg?file=/alert.js

我认为您在这里寻找的是通过 React Router 传递状态。现在您的警报没有更新,因为您的 URL 在按下提交按钮时正在更改。

Check out this sandbox。我正在传递一条消息和一个 属性 以获取警报以在 / 路由内以不同的逻辑呈现。

这是关键片段:

<Button
  color="primary"
  autoFocus
  component={RouterLink}
  to={{
    pathname: "/",
    state: { message: "hello, i am a state message", open: true }
  }}
>
  Submit
</Button>

然后在 url / 处的警报组件中,您可以:

  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    props.location.state?.open ? setOpen(true) : setOpen(false);
  }, [props]);

  // This message is what is being passed. Could be anything.
  console.log(props.location.state);