React三元运算符首先显示“:”块。为什么?

我有一个简单的react应用程序,其中将Firebase中的当前用户传递到Header组件中。如果用户已登录,则我要显示“登录”链接,如果不是,则要显示“登录”链接。该代码有效,但是如果用户登录,则该代码首先显示“ SIGN-IN”,然后切换到“ SIGN OUT”,而不仅仅是显示“ SIGN OUT”。首次加载页面时,该开关非常明显。如果用户已登录,如何使它永远不显示登录?

标头:

const Header = ({ currentUser }) => {
    return (
        <div className="top-nav">
            <ReactSVG src={crown}/>
            <div className="links">
                <Link to="/shop">SHOP</Link>
                <Link to="/contact">CONTACT</Link>
                {
                    currentUser ? <div onClick={() => auth.signOut()}>SIGN OUT</div>
                                : <Link to="/sign-in">SIGN-IN</Link>
                }
                <Link to="/cart">CART</Link>
            </div>
        </div>
    )
}
export default Header;

应用程式:

class App extends Component {
    constructor() {
        super();
        this.state = {
            currentUser: null
        }
    }

    componentDidMount() {
        auth.onAuthStateChanged(user => {
            this.setState({ currentUser: user});
            console.log(user);
        });
    }

    componentWillUnmount() {
        auth.signOut();
    }

    render() {
        return (
            <>
                <Header currentUser={this.state.currentUser}/>
                <Switch>
                    <Route exact path="/" component={HomePage}/>
                    <Route path="/sign-in" component={CredentialsPage}/>
                    <Route path="/shop" component={ShopPage}/>
                    <Route path="/shop/hats" component={Hats}/>
                    <Route path="/shop/jackets" component={Jackets}/>
                    <Route path="/shop/sneakers" component={Sneakers}/>
                    <Route path="/shop/womens" component={Womens}/>
                    <Route path="/shop/mens" component={Mens}/>
                </Switch>
            </>
        )
    }
}
export default App;
评论
  • peum
    peum 回复

    onAuthStatedChanged和setState都是异步的。 您的初始状态为currentUser:空。这是首先呈现出来的东西。只有这样,异步调用解析后,状态才包括您的currentUser。如果要防止延迟,则应跟踪获取状态并推迟该组件的渲染(可能带有指示器或什么也不显示)