Laravel 的奇怪行为 - 反应路由器和后退按钮

比利瓦尔

我正在用 laravel 构建一个天气应用程序(几乎完成),我决定用 react/redux/react-router 实现前端,并使用 api 调用中的 laravel。我决定保持不变的唯一一件事是我的自定义 laravel auth 实现,其中包含路由和视图。它的工作方式是:身份验证受到控制,但 laravel 和当用户登录时,被重定向到刀片视图(由 laravel auth 中间件分组),从那里反应路由器控制。

但是,我面临后退按钮的问题。当使用 react-router 导航并点击注销按钮(指向 laravel 注销路由的链接)时,页面会像预期的那样重定向到欢迎页面,但使用后退按钮返回到存在 react-router 和 react 组件的上一页。但是之后,当我手动刷新页面时,它会将我重定向到登录页面。(总而言之,一切正常,但我想在注销后以某种方式清除路由器历史记录,并且不允许用户返回)

我看到很多关于 react-router 和操纵历史的讨论,但没有一个奏效。

有人能帮我吗?

这是代码:

路由文件

Route::get('/', function (){
    return view('welcome');
})->middleware('guest');

Auth::routes();

Route::view('/dashboard', 'main')->middleware('auth');

Route::view('/categories', 'main')->middleware('auth');

主刀片.php

<!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <title>
            ..
        </title>
        <meta content='width=device-width, initial-scale=1.0, 
          maximum-scale=1.0, user-scalable=0, shrink-to-fit=no'
          name='viewport' />
    </head>
    <body>
        <div id="app_component"></div>
        <!--   Core JS Files   -->
        <script>
            window.Laravel = {!! json_encode([
            'csrfToken' => csrf_token(),
            'apiToken' => auth()->user()->api_token ?? null,
        ]) !!};
        </script>
        <script src="{{ mix('js/app.js') }}"></script>
    </body>
    </html>

app.js(导入后)

if (document.getElementById('app_component')) {

    axios.defaults.headers.common['Authorization'] = 'Bearer ' + Laravel.apiToken;

    let store = configureStore();

    let jsx = (
        <Provider store={store}>
            <AppRouter/>
        </Provider>
    );

    let saveDataAndRenderApp = () => {
        ReactDOM.render(jsx, document.getElementById('app_component'))
    }

    store.dispatch(startCheckAuth()).then(()=>{      *** axios call
        store.getState().checkAuth.auth ?
            saveDataAndRenderApp()
            :
            store.dispatch(startLogoutUser()).then(()=>{
            location.assign('localhost/logout')
        })
    });
}

Approuter.js(导入后)

export const history = History();

class AppRouter extends React.Component {
    render(){
        return (
            <Router history={history}>
                <div className="wrapper">
                    <Sidebar/>
                    <div className="main-panel">
                        <Navbar/>
                        <Switch>
                            <Route path='/dashboard' component={Dashboard} exact/>
                            <Route path='/categories' component={Category} exact/>
                            <Route path='/create' component={Create} exact/>
                            <Route component={NotFound}/>
                        </Switch>
                    <Footer/>
                    </div>
                </div>
            </Router>
        );
    }
}

export default connect()(AppRouter)  

Header 组件内的注销按钮

    class NavbarUI extends React.Component {
        constructor(props){
            super(props);
            this.logout = this.logout.bind(this)
        }
        logout(){
            this.props.dispatch(startLogoutUser()).then(()=>{
                location.assign('localhost/logout')  
            })
        }
        render() {
            return (
                <nav >...
<button onClick={this.logout}>Logout</button>              
                </nav>
            );
        }
    }

    export default withRouter(connect()(NavbarUI))

和行动

let logoutUser = () => {
    return {
        type: 'LOGOUT'
    }
}

export let startLogoutUser = () => {
    return (dispatch) => {
        return new Promise((resolve)=>{
            dispatch(logoutUser())
            resolve()
        })
    }
}
比利瓦尔

我的问题解决了在 laravel 中创建一个中间件,它可以防止缓存控制并应用于我针对带有 react-router 实现的视图的每个路由。

也许对于将 react/react-router 与 laravel 结合使用的人可能会有所帮助,因为有人可能面临同样的情况。

非常感谢 Remul 评论我的解决方案

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章