2017-06-01 69 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生命周期函数中解析和设置状态。

相关问题