Реакции-роутер v2 - заменить в onEnter не работает

В моем приложении я использую реагирующий маршрутизатор v2 - https://github.com/reactjs/react-router

У меня проблема с перенаправлением в onEnter:

какой-то компонент

static async onEnter({ flux }, nextState, replace, callback) {
    const token = flux.getStore('auth').getAccessToken();
    if (!token) {
        replace('/login');
        return callback();
    }
}

Я использую рендеринг на стороне сервера и использовал это руководство - https://github.com/reactjs/react-router/blob/master/docs/guides/ServerRendering.md#async-routes как в нем сказано, что мне нужно использовать match на клиенте тоже:

client.js

RouterMatch({history: browserHistory, routes: patchedRouteHooks(routes)}, (error, redirectLocation, renderProps) => {
    // renderProps are `undefined` when replace from onEnter hook
    ReactDOM.render(
        <Router {...renderProps} createElement={passFluxToComponent} />,
        mountNode,
    );
});

routes.js

const routes = (
    <Route path="/" component={AppHandler}>
        <Route path="/" component={AuthHandler}>
            <Route path="login(/)" component={LoginFormHandler} />
            <Route path="signup(/)" component={SignupFormHandler} />
            <Route path="resetpassword(/)" component={ResetPasswordFormHandler} />
            <Route path="changepassword(/)" component={ChangePasswordFormHandler} />
            <Route path="logout(/)" component={LogoutHandler} />
        </Route>

        <Route path="/" component={AppLayoutHandler}>
            <Route path="/" component={EnsureAuthHandler}>
                <Route path="me/favorites(/)" component={FavoritePropertiesHandler} />
                <Route path="me/settings(/)" component={UserSettingsHandler} />
                <Route path="dashboard(/)(:status)(/)" component={DashboardFlowHandler} />
                <IndexRoute component={DashboardFlowHandler} />
            </Route>

            <Route path="/s(/)" component={SearchResultsHandler} />
            <Route path="/user/:id(/)" component={UserDetailsHandler} />
            <IndexRoute component={EnsureAuthHandler} />
        </Route>

        <IndexRoute component={AppLayoutHandler} />
    </Route>
);

export default routes

patchRouteHooks.js

function patchRouteHooks (Route, patchData = {}) {
    const { props: { children, component } } = Route;

    function _patchChildren (children) {
        if (Array.isArray(children)) {
            return React.Children.map(children, ChildRoute => patchRouteHooks(ChildRoute, patchData));
        } else {
            return patchRouteHooks(children, patchData);
        }
    }

    return {
        ...Route,
        props: {
            ...Route.props,
            onEnter: component && component.onEnter && function (...args) {
                component.onEnter.call(null, patchData, ...args);
            },
            onLeave: component && component.onLeave && function (...args) {
                component.onLeave.call(null, patchData, ...args);
            },
            children: children ? _patchChildren(children) : null
        }
    };
}

export default patchRouteHooks;

После замены в onEnter я получаю renderProps как undefined что приводит к предупреждениям в консоли и неработающему приложению:

Есть предложения, что я делаю не так? Спасибо!

1 ответ

Как вы говорите, renderProps undefined,

Вместо того чтобы передавать renderProps, я сделал что-то, что примерно соответствует вашему случаю:ReactDOM.render( <Router history={browserHistory} routes ={patchedRouteHooks(routes)} createElement={passFluxToComponent} />, mountNode, );

Не в состоянии полностью понять, что сопоставление выполняется асинхронно, и имея совершенно функциональное приложение (с рендерингом сервера) без него, я просто перестал его использовать:)

Вы можете сохранить текущую реализацию (с соответствием) и обернуть ваш запасной рендер в

if (redirectLocation) { ...my proposition } else { ...your implementation }

Другие вопросы по тегам