javascript - 使用 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
解决方案
我认为您在这里寻找的是通过 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);
推荐阅读
- c# - 从 C# 向 Salesforce 批量或批量插入记录
- android - Gmail 通知如何运作?(安卓)
- php - Codeigniter 选择 SUM 给 mysqld cpu 高
- python - 循环一个函数(包括输入),直到按下特定的输入
- optaplanner - Optaplanner 结果不可重现
- r - 计算R中3个变量之间的相关性
- python - Scipy t-test 测量两个文档中使用词典的差异
- c# - 如何从某个日期开始每 14 天执行一次 Hangfire 作业
- r - 使用“read.GenBank”连接到 NCBI 以访问蛋白质序列时出现 R 错误
- java - 例外:NoClassDefFoundError:com/microsoft/azure/storage/CloudStorageAccount