我在下面的 Flow 类型检查中遇到了这个错误。
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");
错误已修复,我希望这对其他人有用,但我很想了解导致此错误的原因。谁能告诉我这是什么?
最佳答案
Aleksey L.在评论中首先得到这个,我想把这个信息带到答案级别以便于视觉扫描。
Flow 让您知道调用 document.getElementById("root");
可以返回 null
,在这种情况下应用程序将完全崩溃。因此,让我们防范这种情况:
const root = document.getElementById('root')
if (root !== null) {
ReactDOM.render(<App /> , root)
}
当然,考虑到您很可能会控制要渲染到的 HTML,这可能会让人觉得有点烦人。
关于javascript - 为什么 Flow 不能用 document.getElementById(...) 调用 ReactDOM.render,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50596022/