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 (将#修改为@)