使用服务器端React的Redux操作中的URL重定向&反应路由器v4

时间:2018-05-14 22:56:57

标签: reactjs redirect redux react-router-v4 serverside-rendering

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

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

1 个答案:

答案 0 :(得分:0)

如果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));
&#13;
&#13;
&#13;