如何在Redux中实现从根到根(index.js)的路由

时间:2019-06-01 17:44:14

标签: javascript reactjs redux

我正在编写一个反应服务器网页,试图从index.js(即localhost:3000)重定向到登录页面:(localhost:3000 /登录),并从登录到索引(如果登录失败)我需要写index.js吗?和login.js?

这是针对基于React的应用程序,也使用redux框架。我尝试了几种方法,包括设置BrowserRouter等。所有方法实际上都不会进行重定向。

我当前的代码是这样:

在index.js中:

class Index extends Component {
    static getInitialProps({store, isServer, pathname, query}) {
    }

    render() {
        console.log(this.props);
        //const hist = createMemoryHistory();
        if (!this.props.isLoggedIn){
            return(<Switch><Route exact path = "/login"/></Switch>)
        }
                else{...}

在login.js中:

render() {
        console.log(this.props);
        if (fire.auth().currentUser != null) {
            var db = fire.firestore();
            db.collection("users").doc(fire.auth().currentUser.uid).get().then((doc) => {
                this.props.dispatch({ type: 'LOGIN', user: doc.data() });
            })
        }
        const { isLoggedIn } = this.props
        console.log(isLoggedIn)

        if (isLoggedIn) return <Redirect to='/' />

除了没有会话的情况下,我将root重定向到登录,并且在成功登录后将登录重定向到root。 我目前在索引处收到“您不应该在外部使用”(我尝试用BrowserRouter,ServerRouter,Router包装。第一个表示它需要DOM历史记录。添加历史记录不会更改错误。另外两个没有错误,但是为空在浏览器上显示。) 和“ ReferenceError:未定义重定向”。

任何帮助将不胜感激。 谢谢, 阿隆

2 个答案:

答案 0 :(得分:0)

到目前为止,您正在尝试返回包装在Switch组件中的路由声明。如果要在用户未登录的情况下将其重定向到/ login页面,则需要在组件层次结构中将路由声明为更高的位置,然后才能返回该组件。无论哪种方式,我都建议您查看React Router文档,以了解它们如何进行身份验证。

https://reacttraining.com/react-router/web/example/auth-workflow

答案 1 :(得分:0)

您可以使用HOC(Higher-Order Components) 像这样

public partial class WpfControl : UserControl
    {
        public WpfControl()
        {
            InitializeComponent();
        }

        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            base.OnPreviewKeyDown(e);
        }
    }