首页 > 解决方案 > 使用 Material UI Web 组件在两个页面之间传递一个布尔值 useState

问题描述

我一直在尝试useState在两个页面之间传递一个布尔值,使用此处显示的最佳实践:如何从另一个页面调用 useState?

我的主要目标是在成功提交表单后在不同页面上显示成功警报"./demo"

Demo.js包含一个对话框,其中 asubmit 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设置为 true。

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

标签: javascriptreactjsreact-hooksuse-state

解决方案


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

看看这个沙箱。我正在传递一条消息和一个属性,以使警报以/不同的逻辑在路由中呈现。

这是关键片段:

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

推荐阅读