所有数据准备就绪后加载组件

Mar*_*rin 5 javascript reactjs redux

我正在使用React和Redux.在这个例子中,我的class有mapStateToPropsmapDispatchToProps

class EnigmaPage extends Component {

    constructor(props){
        super(props);
    }

    componentDidMount() {
        this.props.authCheckState();
    }

    readUserData() {
        this.props.loadLevel(this.props.userId);
    }

    render(){
        return (
            <div className={classes.EnigmaPage}>
                <div className={classes.Header}>
                    <div>
                        <LevelInfo 
                            difficulty={this.props.level.difficulty}
                            level={this.props.level.level}
                            readUserData={this.readUserData()}
                        />

                    </div>
                </div>
            </div>
        )
    }

}

const mapDispatchToProps = dispatch => {
    return {
        authCheckState: () => dispatch(actions.authCheckState()),
        getLevel: () => dispatch(actions.getLevel()),
        loadLevel:(id) => dispatch(actions.loadLevel(id))
    };
}
const mapStateToProps = state => {
    return {
        userId:state.auth.user,
        level:state.level.level
    }
}
Run Code Online (Sandbox Code Playgroud)

我想向我的组件LevelInfo推送值难度级别,但是这两个数据来自getLevel(),这是一个带有延迟的http请求.
页面在从http调用接收所有数据之前加载.
我正在寻找一种等待加载组件LevelInfo或在数据准备就绪时重新加载组件的方法.

Juo*_*lez 6

您需要告诉您的组件将等待渲染Level组件所需的数据,因此在EnigmaPage组件中写入如下

render(){
    const { level } = this.props;
    if (!level) { return <LoadingComponentSpinner />; } // this will render only when level attr is not set, otherwise will render your `LevelInfo` component
    return (
        <div className={classes.EnigmaPage}>
            <div className={classes.Header}>
                <div>
                    <LevelInfo 
                        difficulty={this.props.level.difficulty}
                        level={this.props.level.level}
                        readUserData={this.readUserData()}
                    />

                </div>
            </div>
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

我希望它可以帮到你.