2017-07-27 82 views
1

我正在做一个条件在我的shouldComponentUpdate方法,如果条件匹配返回true,否则返回false ...但是我仍然得到“返回未定义,而不是一个布尔...”作为标题暗示。ReactJS警告:Thumbnails.shouldComponentUpdate():返回undefined而不是布尔值。请确保返回true或false

这里是我的方法:*注意:如果我没有它自动假设nextProps.props.length是0甚至当其超过0

shouldComponentUpdate(nextProps){ 
    setTimeout(()=>{ 
     console.log(nextProps.props, nextProps.props.length); 
     if(nextProps.props.length > 0){ 
      return true; 
     }else{ 
      return false; 
     } 
},1000) 
} 
+0

你为什么使用'setTimeout'? –

+0

你正试图实现什么? –

+0

无论setTimeout长度是否为0,它都返回为0,而不管该长度是否为0。我想通了,但我只是在shouldcomponentupdate中使用this.state not this.props或nextProps ...所以这个问题解决了...现在另一个问题,虽然 – moesh

回答

1

你的组件道具实际上是存储在的setTimeout nextProps的说法。看起来你试图访问nextProps中的props,这显然看起来很腥。

如果这真的是你想要达到的目标,你不应该将组件的通道命名为props。给你的组件的道具更多的描述性名称。

此外,在shouldComponentUpdate表达式可以简化为:

shouldComponentUpdate(nextProps){ 
    return nextProps.props.length > 0; // assuming nextProps.props is an array 
} 

此外,你应该张贴您的组件的propTypes定义,因此该组件的道具合同是明确的。