如果不为空,则反应分配值

时间:2019-04-22 15:36:39

标签: reactjs conditional

当我执行以下操作时:

let ContentAreaHeight = document.getElementById('contentArea').clientHeight;

第一次加载页面时出现Cannot read property 'clientHeight' of null错误,这是我的正常现象。因此,我试图提出一个空检查并分配值(如果不为空),就像下面的选项之一一样,但均无效,stil会给出相同的错误。

option1

let ContentAreaHeight = (document.getElementById('contentArea').clientHeight) || 0;

option2

let ContentAreaHeight = (document.getElementById('contentArea').clientHeight !== null) ?
                    document.getElementById('contentArea').clientHeight : 0;

我搜索了很多地方,但没有找到解决方案,这似乎很简单,但实际上没有任何作用。

我将这段代码放在 const content = ({ pageURL, dataStatus }) => { 和     return (

2 个答案:

答案 0 :(得分:0)

您应在致电.clientHeight

之前进行检查
let ContentAreaHeight = document.getElementById('contentArea');
if (ContentAreaHeight) ContentAreaHeight = ContentAreaHeight.clientHeight

答案 1 :(得分:0)

以下是我找到的最佳方法:

let ContentArea = document.getElementById('contentArea');
let ContentAreaHeight = 0;
if(ContentArea != null & ContentArea > 0)
     ContentAreaHeight = ContentArea.clientHeight;

确保将其放置在componentWillUnmount()componentDidUpdate()生命周期内。