首页 > 解决方案 > 如何在与 redux 的反应中实现从根 (index.js) 到根 (index.js) 的路由

问题描述

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

这适用于基于反应的应用程序,也使用 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。我目前在索引处收到“您不应该在 <Router> 之外使用 <Switch>”(我尝试使用 BrowserRouter、ServerRouter、Router 进行包装。第一个说它需要 DOM 历史记录。添加历史记录不会改变错误。另外两个不要出错,但在浏览器上显示为空白。)和登录时“ReferenceError:未定义重定向”。

任何帮助将不胜感激。

标签: javascriptreactjsredux

解决方案


您可以使用类似这样的 HOC(高阶组件)

export default ChildComponent => {
    class ComposedComponent extends Component {

        componentWillMount() {
            this.shouldNavigateAway();
        }
        componentWillUpdate() {
            this.shouldNavigateAway();
        }
        shouldNavigateAway() {
            if (!this.props.authenticated) {
                this.props.history.push('/')
            }
        }

        render() {
            return <ChildComponent {...this.props} />
        }
    }
}

推荐阅读