在服务器获取成功后启动React root render

时间:2017-03-09 11:04:40

标签: reactjs fetch delayed-execution

我想获取一些数据(如翻译/初始设置等),然后启动应用程序

我该如何以最好的方式做到这一点?

现在我渲染一个微调器,在获取成功后我重新渲染React root。 但我不确定这是非常好的方式。

感谢您的帮助!

//launch fetch and wait for the response. After that re -render Root
bootPreparationInit()
    .then(() => {
        render(
            <RHTLContainer>
                <MuiThemeProvider>
                        <RootContainer store={store} history={history} />
                </MuiThemeProvider>
            </RHTLContainer>,
            document.getElementById("root")
        );
    });

// it for tests. Because Karma sometimes can't see the root element
(() => {
    if (!document.getElementById("root")) {
        const rootEl = document.createElement("div");
        rootEl.setAttribute("id", "root");
        document.body.appendChild(rootEl);
    }
})();

//  render a spinner before data load
render(
    <RHTLContainer>
        <MuiThemeProvider>

                <div className="spinner-ico-box">
                    <CircularProgress />
                </div>

        </MuiThemeProvider>
    </RHTLContainer>,
    document.getElementById("root")
);

// it for webpack HMR
if (module.hot) {
    module.hot.accept("./core/containers/Root.container", () => {
        const NewRootContainer = require("./core/containers/Root.container").default;

        render(
            <RHTLContainer>
                <NewRootContainer store={store} history={history} />
            </RHTLContainer>,
            document.getElementById("root")
        );
    });
}

1 个答案:

答案 0 :(得分:0)

我建议在RHTLContainer组件构造函数中获取数据,并在状态下获取成功保存的已获取数据:

constructor() {
     ...
     this.state = {
        dataLoading: true;
     };
     bootPreparationInit()
        .then((responseData) => {
           ...
           this.setState({
               dataLoading: false,
               fetchedData: respondeData
           });
        });
}

然后在组件内部,您可以使用this.state.dataLoading有条件地显示微调器。