【问题标题】:redirecting to logout a user using react router使用反应路由器重定向以注销用户
【发布时间】:2021-09-18 03:38:54
【问题描述】:

当用户单击Are you sure you want to log out? 弹出对话框中的Yes 按钮时,我试图将用户重定向到 URL hostUrl+'logout'。由于我的其他代码部分正在使用 反应路由器,我想知道我是否可以在以下功能中使用相同的功能:

 logoutDialogClose = event =>{
    if (event) {
        this.setState({ displayLogoutPopup: false})
        
       
    }        
}

this post 中的某个人建议使用Link,但不确定这是否适用于我的情况。

完成上述测试后,我可能需要一个单独的函数 logoutDialogYes 以从弹出对话框中分离 CancelYes 的点击。

我的完整代码如下:

const hostUrl = properties.baseUrlUI

class Main extends Component {
    constructor() {
        super();
        this.state = {
          
         
            isAuthenticated: false,
            displayLogoutPopup: false,
            
        };
        this.logoutDialogOpen = this.logoutDialogOpen.bind(this)        
        this.logoutDialogClose = this.logoutDialogClose.bind(this)

    }

    componentDidMount() {
     //some stuff here  
     }

    loadDropDownObjects() {
          // some axios call to store info in session storage
    }

    logoutDialogOpen = event =>{
        if (event) {
            this.setState({ displayLogoutPopup: true})
                      
        }        
    }

    logoutDialogClose = event =>{
        if (event) {
            this.setState({ displayLogoutPopup: false})
            /* <Link to="/">
                <i className="fa fa-sign-out pull-right"></i> 
                Log Out
          </Link> */
          
           /*  console.log("Testing host URL");
            console.log(hostUrl);
            axios.delete(hostUrl+'logout')
            //axios.get(hostUrl+'logout') 
            .then(response => {
                console.log("Reaching inside the response of logoutDialogClose function and printing the response below:");
                console.log(response);
                //keeping the setState outside until we test it on dev server
                //this.setState({ displayLogoutPopup: false})
            })
            .catch (error => {
                console.log("logout error", error);
            }) */
           
        }        
    }
    
    render() {
       
        const logoutDialog = this.state.displayLogoutPopup ? (
            <div className="popup popup--icon -question js_question-popup"
                 id={this.state.displayLogoutPopup ? 'popup--visible' : ''}>
                <div className="popup__background"></div>
                <div className="popup__content">
                    <h3 className="popup__content__title">
                        Are you sure you want to log out?
                    </h3>
                    <p>
                        <button className="button button_accept" onClick={this.logoutDialogClose}>Yes</button>
                        <button className="button button--warning" onClick={this.logoutDialogClose}>Cancel</button>
                    </p>
                </div>
            </div>
        ) : null

        return (
            
            <div>
            {
                this.state.isAuthenticated ? (
                    <BrowserRouter basename={process.env.REACT_APP_ROUTER_BASE || ''}>
                        <div>
                            <div className="header">
                                <div className="header-logo">
                                <img src="images/logo.jpg"/>
                                <span>DATA</span>
                                </div>

                                <div className="logout_sec">
                                <div className="logout_icon">
                                    <a href="javascript:void(0)" onClick={this.logoutDialogOpen}> <FontAwesomeIcon
                                        style={{fontSize: '1.5em'}} icon={faSignOutAlt}/></a>
                                </div>
                                </div>                                

                                <ul className="header-list">
                                <li>
                                    <NavLink exact to="/">
                                        Home
                                    </NavLink>
                                </li>
                                <li>
                                    <NavLink to="/myprojects">My Projects</NavLink>
                                </li>
                                <li>
                                    <NavLink to="/myassets">My Assets</NavLink>
                                </li>
                              
                                <li>
                                    <NavLink to="/datadownload">DataSet Download</NavLink>
                                </li>
                                <li>
                                    <NavLink to="/assetbrowser">Asset Browser</NavLink>
                                </li>
                            </ul>



                                {/* Popup COde start */}

                                {logoutDialog}
                                {/* Popup code End */}
                            </div>

                            <div id="forNotification"></div>
                            <div>
                                <Switch>
                                    <Route exact path="/" component={Home}/>
                                    <Route path="/myprojects"
                                           render={(props) =>
                                               <div>
                                                   <Projects {...props}/>
                                               </div>
                                           }
                                    />
                                    
                                  
                                    <Route exact path="/project" component={ProjectView}/>
                                    <Route exact path="/datadownload" component={DataDownload}/>
                                    <Route exact path="/assetbrowser" component={AssetBrowser}/>
                                    <Route exact path="/datarequest" component={DataRequest}/>
                                    <Route path='/404' component={NotFoundPage}/>
                                    <Redirect to="/404"/>
                                </Switch>
                            </div>
                        </div>
                    </BrowserRouter>
                ) : null
            }
            </div>
        );
    }
}

export default Main;

【问题讨论】:

  • 你可以使用 react 路由器历史来推送到你想要的页面 - reactrouter.com/web/api/history
  • 这能回答你的问题吗? stackoverflow.com/questions/59402649/…
  • 我在使用 useHistory 钩子时不断收到"export 'useHistory' was not found in 'react-router-dom'。我的react-router-dom 版本是4.3.1.。此版本似乎不支持此功能。有没有办法在不使用这个钩子的情况下实现我正在寻找的东西?如果可能,我会尽量不升级react-router-dom 版本。我的反应版本也是16.4.2。对于钩子,根据我的在线研究,我相信它需要 16.8

标签: reactjs react-router


【解决方案1】:

尝试添加此导入:

import {withRouter} from 'react-router-dom';

将导出语句改为:

export default withRouter(Main);

然后,您应该可以通过this.props.history 访问Main 中的历史对象。例如:

logoutDialogClose = event =>{
    if (event) {
        this.setState({ displayLogoutPopup: false})
        
       this.props.history.replace(`/some/path`);
       // OR
       this.props.history.push(`/some/path`);
    }        
}

编辑:

尝试将导出语句替换为:

const MainWithRouter = withRouter(Main);

const MainWrapper = props => (
    <BrowserRouter basename={process.env.REACT_APP_ROUTER_BASE || ''}>
        <MainWithRouter {...props} />
    </BrowserRouter>
);

export default MainWrapper;

【讨论】:

  • 尝试了上述方法。收到 Uncaught Invariant Violation: You should not use &lt;Route&gt; or withRouter() outside a &lt;Router&gt; 错误。当我使用export default withRouter(Main); 时会发生这种情况。如果我将其保留为 export default Main; 并带有您提到的其他更改,则不会引发任何错误。知道可能出了什么问题吗?
  • 你是说去掉 withRouter() 就完全可以用了吗?
  • 我只在底部使用export default Main; 时没有收到错误消息。但是,它不适用于此。我相信我必须先解决我在export default withRouter(Main); 看到的错误。我的react-router-domreact-router 版本是4.3.1,如果这有帮助的话。谢谢!
  • 尝试从Main中删除&lt;BrowserRouter ...&gt;并将导出语句更改为export default &lt;BrowserRouter basename={process.env.REACT_APP_ROUTER_BASE || ''}&gt;withRouter(Main)&lt;/BrowserRouter&gt;
  • 我删除了` ` 和 ` ` 并按照您在导出中提到的那样做,现在出现此错误,如此处的图片链接所示:i.stack.imgur.com/Ta38Y.png
猜你喜欢
  • 2017-10-22
  • 1970-01-01
  • 2019-12-30
  • 1970-01-01
  • 1970-01-01
  • 2018-11-22
  • 1970-01-01
  • 2016-10-10
  • 1970-01-01
相关资源
最近更新 更多