【问题标题】:Best way to restrict page access?限制页面访问的最佳方法?
【发布时间】:2022-01-08 22:42:15
【问题描述】:

我正在设计一个带有表单组件的网站,该组件根据表单提交是否没有错误来重定向到“失败”或“成功”组件。这是我正在使用的代码:

await axios
  .post('/api/patients/', data, axiosConfig)
  .then((response) => {
    history.push('/success');
  })
  .catch((error) => {
    history.push('/failure');
  });

即使我通过关闭网络或更改路由故意发出错误请求,这也能正常工作。但是,我可以在浏览器中输入“/success”路由并访问它,无论我是否提交了表单。如何限制这种行为?

【问题讨论】:

    标签: javascript reactjs react-hooks routes react-router-v4


    【解决方案1】:

    我不确定是否可以跟踪手动输入的路线,但您可以将“提交:true”等“成功”组件道具传递给“成功”组件,并在此道具存在时渲染组件。

    await axios
    .post('/api/patients/', data, axiosConfig)
        .then((response) => {
            history.push({
              pathname: '/success',
              state: { submit: true }
            });
     })
     .catch((error) => {
       history.push({
         pathname: '/failure',
         state: { submit: true }
       });
     });
    

    并且在“成功”组件中检查道具,例如:

    if (props.location.state.submit) { . . . }
    

    【讨论】:

    • 嘿,我在访问 Success 组件中的状态时遇到问题。我应该使用 Redux 或 Context 之类的东西来处理全局状态吗?因为最初我是这么想的,但是每次用户离开成功/失败页面时,我都必须找到一种方法来重置状态
    • @JM223 我认为您可以使用 redux 或本地存储来设置 submit: true 并在成功组件上卸载 set submit: false
    猜你喜欢
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 2019-05-11
    • 2013-09-25
    • 1970-01-01
    • 2011-10-15
    相关资源
    最近更新 更多