为什么Flow无法使用document.getElementById(...)调用ReactDOM.render

时间:2018-05-30 03:39:07

标签: javascript reactjs flowtype

我在流式检查中收到以下错误。

Cannot call ReactDOM.render with document.getElementById(...) bound to container because null [1] is
incompatible with Element [2].

     src/index.js
      26│       </Switch>
      27│     </ScrollToTop>
      28│   </BrowserRouter>
      29│ </Provider>, document.getElementById("root"));
      30│

     /private/tmp/flow/flowlib_174a8121/dom.js
 [1] 646│   getElementById(elementId: string): HTMLElement | null;

     /private/tmp/flow/flowlib_174a8121/react-dom.js
 [2]  18│     container: Element,

代码如下。

// @flow
"use strict";
import React from "react";
import ReactDOM from "react-dom";
import {createStore, applyMiddleware} from "redux";
import {Provider} from "react-redux";
import {BrowserRouter, Switch, Route} from "react-router-dom";
import Home from "./components/home";
import Detail from "./components/detail";
import LevelOfGame from "./components/level-of-game";
import NotFound from "./components/not-found";
import ScrollToTop from "./components/scroll-to-top";

import reducers from "./reducers";

const createStoreWithMiddleware = applyMiddleware()(createStore);

ReactDOM.render(<Provider store={createStoreWithMiddleware(reducers)}>
  <BrowserRouter>
    <ScrollToTop>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/detail/:detailId" component={Detail}/>
        <Route path="/level-of-game" component={LevelOfGame}/>
        <Route path="*" component={NotFound} status={404}/>
      </Switch>
    </ScrollToTop>
  </BrowserRouter>
</Provider>, document.getElementById("root"));

我相信我必须在getElementById中以某种方式指定类型。

所以我通过将document.getElementById("root");存储在具有类型规范的常量变量中来修复错误:

const root: any = document.getElementById("root");

错误已修复,我希望这对其他人有用,但我很想知道导致此错误的原因。任何人都可以如此友善地告诉我这是什么?

2 个答案:

答案 0 :(得分:15)

Aleksey L.在评论中首先提到这一点,我希望将此信息提升到答案级别,以便更轻松地进行视觉扫描。

Flow告诉您,调用document.getElementById("root");可以返回null,在这种情况下,应用会完全崩溃。所以让我们警惕:

const root = document.getElementById('root')

if (root !== null) {
  ReactDOM.render(<App /> , root)
}

当然,考虑到你很可能会控制你正在渲染的HTML,这会让你觉得有点恼火。

答案 1 :(得分:0)

虽然Cogell的答案是正确的,但我还是主张保持代码简单并添加异常。

Integer

注意“ $ FlowIgnore”注释

,然后在您的ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <BrowserRouter> <ScrollToTop> <Switch> <Route exact path="/" component={Home}/> <Route path="/detail/:detailId" component={Detail}/> <Route path="/level-of-game" component={LevelOfGame}/> <Route path="*" component={NotFound} status={404}/> </Switch> </ScrollToTop> </BrowserRouter> </Provider>, // $FlowIgnore document.getElementById("root") ); 文件中,将其添加到“选项”字段:

.flowconfig