如何解决React - 使用 Router
我是 React 的新手,我注意到在 onSubmit
中通过路由器发送状态值时,下一页中 spaghetti
的值有时是错误的。
这是我的一段代码:
const ItalianMenu=()=>{
const history = useHistory();
const spaghettiRef = React.createRef();
const [spaghetti,setSpaghetti] = useState('0');
useEffect(() => {
mounted.current = true; // Will set it to true on mount ...
return () => { mounted.current = false; }; // ... and to false on unmount
},[]);
const SelectSpaghetti = () => {
spaghettiRef.current.select();
};
const onSubmit=(e)=>{
e.preventDefault();
setButtondisabled(true);
setTimeout(()=>{
history.push("/confirmedOrder",{spaghetti,tip});
setSpaghetti('0')
setButtondisabled(false);
},2000)
}
return(
<Grid align="center">
<Paper style={paperStyle}>
<Grid align="center">
<Paper style={italianStyle}>
<h2>The Pink Pomodoro</h2>
</Paper>
</Grid>
<form novalidate autoComplete="off" onSubmit={onSubmit}>
<Grid align="left">
<Grid container>
<Grid item xs={4}>
<Typography style={menuItemStyle}>Spaghetti with Meatballs -
<b>$14</b></Typography>
</Grid>
<Grid item xs={6}>
<Typography style={menuItemStyle}>Spaghetti with meatballs topped with red marinara sauce.</Typography>
</Grid>
<Grid item xs={2}>
<TextField
inputRef={spaghettiRef}
onFocus={SelectSpaghetti}
onChange={(e) => {
if (mounted.current) {
if (Number(e.target.value) > 10) {
setSpaghetti(10)
} else {
setSpaghetti(e.target.value)
}
}}}
value={spaghetti}
type='number'
inputProps={{min: "0",max:"10",style: {
textAlign: "right",margin:"3px" }}}
fullWidth/>
</Grid>
</Grid>
...
关于此问题的结果为零。这是我的目标组件的当前代码。
const ConfirmedOrder=()=>{
const location = useLocation();
return(
<Grid>
<Typography>
{String(location.state.spaghetti)} {location.state.tip}
</Typography>
</Grid>
);
}
那么,为什么我的目标组件会从 italianMenu
接收到错误的状态值?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。