簡體   English   中英

流星和React:根據登錄狀態正確渲染的方式

[英]Meteor and React: Correct way to render according to login state

我有一個具有登錄功能的Meteor + React應用程序。 主導航欄根據用戶的登錄狀態顯示不同的項目。

我的問題是,當用戶登錄時,它不會像預期的那樣自動更新導航欄。 僅在重新加載頁面或更改路線后顯示。

這顯然有悖於使用React。

這就是我所擁有的:

AppContainer

export class AppContainer extends Component {
    constructor(props) {
        super(props)
        this.state = this.getMeteorData()
    }

    getMeteorData() {
        return { isAuthenticated: Meteor.userId() !== null}
    }

    render() {
        return(
            <div className="hold-transition skin-green sidebar-mini">
                <div className="wrapper">
                    <Header isAuthenticated={this.state.isAuthenticated} />
                    <MainSideBar />
                    {this.props.content}
                    <Footer />
                    <ControlSideBar />
                    <div className="control-sidebar-bg"></div>
                </div>
            </div>
        )
    }
}

標頭

export class Header extends Component {
    render() { 
        return (
            <header className="main-header">
                ...
                <nav className="navbar navbar-static-top" role="navigation">
                    <a href="#" className="sidebar-toggle" data-toggle="offcanvas" role="button">
                        <span className="sr-only">Toggle navigation</span>
                    </a>
                    <CustomNav isAuthenticated={this.props.isAuthenticated} />
                </nav>
            </header>
        )
    }
}

CustomNav

export class CustomNav extends Component {
    render() {
        if(this.props.isAuthenticated) {
            navigation = <NavLoggedIn />
        } else {
            navigation = <NavLoggedOut />
        }
        return (
            <div className="navbar-custom-menu">
                {navigation}
            </div>
        )
    }
}

我認為這是幫助解決此問題所需的所有相關代碼,但請告知我是否應該做其他事情。 不確定將道具傳遞通過像我這樣的組件是否正確,如果我也在那里搞亂了,請給我個提示。

非常感謝幫助!

您需要包裝您的組件才能使用流星的反應數據。

AppContainer.propTypes = {
   user: PropTypes.object,
};

export default createContainer(() => {
  return {
    user: Meteor.user(),
  };
}, AppContainer);

用戶對象將存儲在this.props.user 您可以使用它有條件地渲染視圖。

暫無
暫無

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

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