反应路由器v4阻止访问页面

问题描述 投票:1回答:1

在React Router v4 doc中我读到了关于提示阻止离开页面:Prompt to prevent to leave,但直到现在我还没有发现任何关于阻止访问像旧版本中的willtransitionto

有什么建议吗?

react-router react-router-v4
1个回答
1
投票

刚刚研究过这个问题,所以,这里有我带来的例子(我不确定这是不是最好的方式,也许有更好的灵魂,但我仍想分享):

1)当您阻止访问并知道您必须将用户重定向到哪个页面时:

假设您有Home页面和About页面,如果用户试图访问它,您想要询问用户的意图。

所以,在这种情况下,我们可以将这个逻辑放在<Route>组件中的render属性中,就像这样

render={(props)=>{
          if(confirm('Are you sure you want to see this page?')){
            return <About />
          } else {
            return <Redirect to='/'/>
          }
        }
      }

因此,如果用户点击OK它将显示About页面,否则它会将用户重定向到Homepage

class App extends React.Component{
  render(){
    return(
    <Router>
      <div className="container">
        <ul>
         <li><Link to="/">Home</Link></li>
         <li><Link to="/about">About</Link></li>
       </ul>
      <hr/>
      <Route exact path="/" component={Home} /> 
      <Route path="/about" render={(props)=>{
              if(confirm('Are you sure you want to see this page?')){
                return <About />
              } else {
                return <Redirect to='/'/>
              }
            }
          }/>
     </div>
    </Router>
    )
  }
}

完整的例子是here

2)与第一个示例相同,但是如果您想要将用户重定向到用户尝试访问About页面的同一页面上。

在这种情况下,为了确保App组件获取位置信息,我把它包装起来像这样:

<Router>
    <Route path="/" render={
           (props)=>{
               return <App {...props}/>
           }
    } /> 
</Router>

然后在这里,在主要的应用程序组件(App)中,我们可以像这样跟踪路径(因此,每当App从ReactRouter组件获取有关位置和内容的新属性时,我们可以检查它并保存在我们的state中):

  constructor(props){
        super(props);

        this.state={
            prevPath: props.location.pathname
        }
    }

   componentWillReceiveProps(nextProps) {
        if (nextProps.location !== this.props.location) {
          this.setState({ prevPath: this.props.location.pathname })
        }
    }

然后,如果用户想要转到about页面,我们可以,如果用户没有确认重定向,请将他带回到上一页,因此,render属性将如下所示:

 <Route path="/about" render={(props)=>{
                if(confirm('Are you sure you want to see this page?')){
                  return <About />
                } else {
                  let toPath = '/';
                  if(this.state.prevPath){
                    toPath=this.state.prevPath
                  }

                  return <Redirect to={toPath}/>
                }
              }
            }/>

完整的例子here

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.