【问题标题】:React router not redirecting on server反应路由器没有在服务器上重定向
【发布时间】:2016-09-15 05:46:53
【问题描述】:

我有一个高阶组件,它检查用户是否经过身份验证,如果没有,将重定向到不同的 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 });
    });
}

【问题讨论】:

  • 你已经“关闭”了 JS。您希望它如何工作?
  • 它是一个使用 node.js 的同构应用程序

标签: javascript reactjs react-router


【解决方案1】:

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

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

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

const userIsInATeam = (nextState, replace) => {
  if ( !isAuth ) {
    replace('/')
  }
}

<Route path="/users/:userId/teams" onEnter={userIsInATeam} />

我认为nextState 应该有你正在寻找的auth 属性来检查身份验证。

【讨论】:

  • 谢谢 - 它现在看起来好像重定向回根目录,但现在出现两个新错误 Warning: Failed prop type: Invalid prop 'children' supplied to 'Route'. in RouterWarning: [react-router] Location "/" did not match any routes
  • 忽略 - 还需要将 const routes = createRoutes(store); 添加到客户端。将此标记为正确答案 - 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-22
  • 2018-08-13
相关资源
最近更新 更多