簡體   English   中英

如何在與redux的反應中實現從和到根(index.js)的路由

[英]How to implement routing from and to root (index.js) in react with redux

我正在編寫反應服務器網頁,嘗試從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。 我目前正在“你不應該在索引處使用<Switch>”之外的<Switch>(我已經嘗試用BrowserRouter,ServerRouter,Router包裝。第一個說它需要DOM歷史記錄。添加歷史記錄不會改變錯誤。另外兩個不要出錯,但在瀏覽器上顯示為空白。)和登錄時“ReferenceError:Redirect未定義”。

任何幫助將不勝感激。

截至目前,您正在嘗試返回包含在Switch組件中的路由聲明。 如果您想要將用戶重定向到/ login頁面,如果他沒有登錄,則需要在組件層次結構中將路由聲明為更高,然后您就可以返回<Redirect />組件。 無論哪種方式,我建議你查看反應路由器文檔,看看他們如何進行身份驗證。

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

你可以使用像這樣的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} />
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM