显示空白页以停止闪烁直到反应获取数据

时间:2018-03-16 04:46:56

标签: reactjs

我有一个页面调用api端点来获取一些数据,并查看他们是否已登录。

如果我在构造函数中将session设置为false,并且是否延迟获取componentDidMount上的数据,则在fetch返回之前显示false的条件内容,将session设置为true并显示内容为真。

现在要隐藏闪烁,我将会话设置为null以呈现空白页直到数据返回。有更好的方法吗?

class Settings extends React.Component {
    constructor(props) {
        super(props);   
        this.state = {
            session: ""
        }
    }

    componentDidMount() {
        // possible delayed fetch response
        this.setState({ session: true })
    }

    render() {
        const {session} = this.state;
        { 
            if (session === true) {
                return (<h1>logged in</h1>)
            } else if (session === false) {         
                return (<h1>not logged in</h1>)
            } else {
                return null;
            }
        }   
    }
}

export default Settings;

1 个答案:

答案 0 :(得分:0)

只需在构造函数中将会话设置为null,并在render方法中显示加载,直到获取会话结果。对于演示,我添加了一个超时来显示加载。此外,除非异步状态更改,否则请尝试不要在componentDidMount中设置状态,因为使用constructor可以实现相同。

class Settings extends React.Component {
    constructor(props) {
        super(props);   
        this.state = {session: null};
    }

    componentDidMount{
        setTimeout(() => this.setState({session: true), 500) // only to simulate fetching session data
    }  

    render() {
        const {session} = this.state;
        if(session === null){
          return <div>...loading</div>
        }
        if (session) {
            return (<h1>logged in</h1>)
        } 
        return (<h1>not logged in</h1>)
    }
}

export default Settings;