React路由器不在服务器上重定向

Pau*_*aul 6 javascript reactjs react-router

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

它是一个同构的应用程序,这适用于客户端,但如果我关闭JS,服务器不会重定向.

if (!this.props.authenticated) {
    this.context.router.push('/');
}
Run Code Online (Sandbox Code Playgroud)

我可以在服务器上点击这个语句并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);
}
Run Code Online (Sandbox Code Playgroud)

并通过路径文件到达此组件:

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>
);
Run Code Online (Sandbox Code Playgroud)

这是服务器呈现代码:

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 });
    });
}
Run Code Online (Sandbox Code Playgroud)

Dre*_*ter 1

可以分享一下你的服务器渲染代码吗?它可能需要看起来像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} />
Run Code Online (Sandbox Code Playgroud)

我认为nextState应该有auth您正在寻找的道具来检查身份验证。