如何在 React 中加载组件之前显示加载微调器

dra*_*agi 3 loading spinner reactjs

我的问题不像标题那么简单。我试图显示一个加载组件 1 秒,然后用实际数据替换该组件。

这是我的代码:

const TopNavigationAuth = () => (
<Container>
    <Menu.Item
        name="landing"
        content="Landing"
        as={Link}
        to={routes.LANDING}
    />
    <Menu.Item name="home" content="Home" as={Link} to={routes.HOME} />
    <Menu.Menu position="right">
        <Menu.Item
            name="account"
            content="Account"
            as={Link}
            to={routes.ACCOUNT}
        />
        <UserSection />
        <Menu.Item
            name="signout"
            content={
                <Button
                    content="Sign Out"
                    onClick={authFunctions.doSignOut}
                    primary
                />
            }
        />
    </Menu.Menu>
</Container>
);
Run Code Online (Sandbox Code Playgroud)

所以这里我有一个<UserSection />组件,它基本上只保存用户的图片和姓名(现在)。我想在 1 或 2 秒后加载该组件,但在那之前我想显示一个微调器。

我正在为我的应用程序使用语义 ui react,它们有一个方便的微调器,如下所示:

const LoaderExampleInlineCentered = () => <Loader active inline='centered' />
Run Code Online (Sandbox Code Playgroud)

我可以请一些指导吗?

小智 5

您可以有条件地渲染两个组件之一,Loader 或 UserSection。

this.state.profileExist === true ? <UserSection /> : <Loader />
Run Code Online (Sandbox Code Playgroud)

然后在 componentDid 挂载中将 profileExist 初始化为 False,然后使用 setTimeout 将其设置为 true

componentDidMount() {
    this.setState({profileExist: false})
    setTimeout(() => { 
          this.setState({profileExist: true})
    }, 1000);
}
Run Code Online (Sandbox Code Playgroud)