React路由器在服务器上没有重定向

React router not redirecting on server

本文关键字:重定向 服务器 路由器 React      更新时间:2023-09-26

我有一个高阶组件,检查用户是否经过身份验证,如果没有将重定向到不同的url。

这是一个同构应用程序,它在客户端工作,但如果我关闭JS,服务器不会重定向。

if (!this.props.authenticated) {
    this.context.router.push('/');
}

我可以在服务器上点击这条语句,this.context.router返回,但是什么也没有发生。

完整组件:

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
export default function (ComposedComponent) {
    class Authentication extends Component {
        static contextTypes = {
            router: React.PropTypes.object
        }
        static propTypes = {
            authenticated: PropTypes.bool
        }
        componentWillMount() {
            if (!this.props.authenticated) {
                this.context.router.push('/');
            }
        }
        componentWillUpdate(nextProps) {
            if (!nextProps.authenticated) {
                this.context.router.push('/');
            }
        }
        render() {
            return <ComposedComponent {...this.props} />;
        }
    }
    function mapStateToProps(state) {
        return { authenticated: state.auth.authenticated };
    }
    return connect(mapStateToProps)(Authentication);
}

,这个组件通过路由文件到达:

export default (
    <Route path='/' component={App}>
        <IndexRoute component={Welcome} />
        <Route path='/feature' component={requireAuth(Feature)} />
        <Route path='/signin' component={Signin} />
        <Route path='/signout' component={Signout} />
        <Route path='/signup' component={Signup} />
    </Route>
);

这是服务器渲染代码:

import { RouterContext, match } from 'react-router';
import { Provider } from 'react-redux';
import { renderToString } from 'react-dom/server';
import React from 'react';
import reactCookie from 'react-cookie';
import configureStore from '../../shared/store';
import routes from '../../shared/routes';
import assets from '../../public/assets.json';
import { AUTH_USER } from '../../shared/actions/types';
export default function (req, res) {
    match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
        if (error) return res.status(500).send(error.message);
        if (redirectLocation) return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
        if (!renderProps) return res.status(404).send('Page not found');
        const store = configureStore();
        // use cookies to retrieve token
        const unplug = reactCookie.plugToRequest(req, res); // eslint-disable-line no-unused-vars
        const token = reactCookie.load('token');
        // if we have a token, consider the user to be signed in
        if (token) {
            // we need to update application state
            store.dispatch({ type: AUTH_USER });
        }
        const content = renderToString(
            <Provider store={store}>
                <RouterContext {...renderProps} />
            </Provider>
        );
        const initialState = JSON.stringify(store.getState());
        return res.render('index', { content, assets, initialState });
    });
}

你能分享你的服务器渲染代码吗?它可能需要看起来像https://github.com/ReactTraining/react-router/blob/master/docs/guides/ServerRendering.md,在这里您正在检查redirectLocation标志。redirectLocation可以通过使用onEnter钩子而不是包装器组件返回。onEnter钩子的文档在这里。

从下面的评论更新:好的,所以你的服务器代码正确检查redirectLocation,但是路由代码需要使用onEnter钩子来正确设置redirectLocation。像这样:

好的,所以你在服务器代码中正确地尊重redirectLocation,但redirectLocation只使用onEnter钩子填充,如下所示:

const userIsInATeam = (nextState, replace) => {
  if ( !isAuth ) {
    replace('/')
  }
}
<Route path="/users/:userId/teams" onEnter={userIsInATeam} />

我认为nextState应该有你正在寻找的auth道具来检查授权。

相关文章: