Why Flow cannot call ReactDOM.render with document.getElementById(…)

前端 未结 2 1547

I was getting this error below in Flow type checking.

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


        
相关标签:
2条回答
  • 2021-02-19 06:23

    While Cogell's answer is correct, I would argue to keep the code simpler and add an exception.

    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")
    );
    

    Notice the "$FlowIgnore" comment

    and then in your .flowconfig file add this to the "options" field:

    suppress_comment= \\(.\\|\n\\)*\\$FlowIgnore

    0 讨论(0)
  • 2021-02-19 06:25

    Aleksey L. got this first in the comments, I wanted to bring this info up to the answer level for easier visual scanning.

    Flow is letting you know that the call document.getElementById("root"); can return null in which case the app would completely crash. So let's guard against that:

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

    Granted, this can feel a little annoying given that in all likelihood you will be controlling the HTML you are rendering into.

    0 讨论(0)
提交回复
热议问题