2017-06-01 68 views
0

我有一個數組來作爲一個字符串(現在不能改變它)。 我收到該字符串,需要對字符串數組執行JSON.parse(),以使其再次成爲數組。 我無法在componentDidMount函數中執行此操作,因爲在Redux中使用狀態組件不是最佳做法。我可以在渲染函數中做到這一點,但就我而言,這並不是一個最佳實踐,可以在那裏對值進行變異。在Redux/React組件中改變道具值的正確方法是什麼?

render() { 
if (typeof this.props.detectedPersonListJson == 'string'){ 
     var array= JSON.parse(this.props.detectedPersonListJson); 
    } 
return (
     <div> 
    array.map(...) 
</div> 

那麼如何在Redux的表現組件中管理道具變異? 謝謝!

+0

爲什麼不在動作中解析它,然後再將它放入reducer中。它只會發生一次。 –

回答

1

我絕對不會在渲染函數中做突變,因爲它會被調用很多。 我會建議閱讀ComponentDidMount中的初始道具,讓它們相應地進行變異並將其存儲在內部狀態中。之後,如果值可能改變,那麼我會建議在ComponentWillReceiveProps中執行相同的突變。 我也不認爲改變給定的道具來使用它們是不好的做法。只要儘量保持突變到最低限度,並使它們遠離渲染函數。

2

如果使用的是終極版,我假設你已經在使用一個mapStateToProps功能,你可以在那裏解析它,並將其提供給陣營組件

function mapStateToProps(state) { 
    var array; 
    if (typeof state.detectedPersonListJson == 'string'){ 
     array= JSON.parse(state.detectedPersonListJson); 
    } 
    return { 
     detectedPersonListJson: array 
    } 

} 

否則,你可以保存道具作爲因爲componentWillMount只被調用一次,componentWillReceiveProps在其後的每個渲染上被調用,因此您需要在componentWillReceivePropscomponentWillMount/componentDidMount生命週期函數中解析和設置狀態。

相關問題