2017-06-22 45 views
1

假設inputvalue={this.state.searchValue}在使用setState清除它之前,您應該檢查輸入是否爲空?

onClose =() => { 
    this.setState({searchValue: ''},() => { 
     this.search(); 
    }); 
    } 

這是浪費,如果容器已關閉,而字符串已空?

應該這樣做嗎?

onClose =() => { 
    if (!isEmpty(this.state.searchValue)) { 
    this.setState({searchValue: ''},() => { 
     this.search(); 
    }); 
    } 
} 

如果這是Redux狀態?

onClose =() => { 
    if (this.props.inputValue) { 
    this.props.clearInput(); 
    } 
} 

我覺得Redux是有點小聰明,並做了shouldComponentUpdate給你,所以它會實現this.props.inputValue === ''nextProps.inputValue === '',節省了渲染?

回答

1

只要調用了setState(),React就會渲染組件。如果你想防止這種行爲,你的組件可以擴展React.PureComponent,它會比較以前的狀態值,以決定是否渲染。

當您用Redux.connect包裝組件時,默認情況下它也會在shouldComponentUpdate中應用淺層比較。

+0

只要檢查'!isEmpty(this.state.searchValue)'是否也工作/我應該做這些檢查? – kayla

相關問題