首页 > 解决方案 > 使用服务器端 React 和 React Router v4 在 Redux 操作中进行 URL 重定向

问题描述

长期以来,我一直试图找出使用 react-router v4 和 redux 处理服务器端呈现的 react 应用程序重定向的最佳方法。

我的应用程序从 API 获取数据 - 有时 API 的响应方式使我需要自动将用户重定向到另一个 URL。

标签: reactjsredirectreduxreact-router-v4server-side-rendering

解决方案


如果 API 以导致我需要重定向的方式响应,我将用户应该被定向到的路径存储在 redux 存储中。(我的 API 返回一个带有“重定向”变量的错误对象,我可以在我的路由文件中查找以作为重定向路径插入到存储中)。

重要的是,这只是将路径存储在 redux 存储中。

case (typeof error["redirect"] !== "undefined" && error["redirect"] !== null): {
    dispatch({
        type: RENDER_REDIRECT,
        payload: routes[error["redirect"]]
    });
    break;
}

我有一个名为“RenderRedirect”的组件,该组件始终在主应用程序中呈现,但如果 this.props 将重定向显示为“null”并且 nextProps 重定向显示为!null,则会采取特殊操作。

这意味着已触发重定向。

它使用 history.push 更改 URL,然后使用另一个操作将重定向清除出存储。

这特别好用,因为我不必担心服务器端渲染错误,因为这种情况只会发生在客户端。

每当我需要触发重定向时,我都可以轻松地以路径作为有效负载来调度上述操作。

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from "react-router-dom";
import { clearRedirect } from '../../../actions';

class RenderRedirect extends Component {

    componentWillReceiveProps(nextProps) {
        // Detect redirect, perform redirect, clear redirect
        const { redirect, history, clearRedirectAction } = this.props;

        // Detect redirect
        if(redirect === null && nextProps.redirect !== null) {
            history.push(nextProps.redirect);
            clearRedirectAction();
        }
    }

    render() {
        const { redirect } = this.props;

        if (redirect !== null) {
            return (
                <div>
                    <p className={"profile-instructions"}>Redirecting...</p>
                </div>
            )
        } else {
            return null;
        }
    }
}

const mapStateToProps = (state) => ({
    redirect: state.redirect
})

const mapDispatchToProps = (dispatch) => ({
    clearRedirectAction: () => dispatch(clearRedirect())
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(RenderRedirect));


推荐阅读