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

前端 未结 2 1539

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: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( , root)
    }
    

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

提交回复
热议问题