【问题标题】:What's the correct way to mutate props value in Redux/React components?在 Redux/React 组件中改变 props 值的正确方法是什么?
【发布时间】:2017-11-02 11:42:02
【问题描述】:

我有一个以字符串形式出现的数组(目前无法更改)。 我收到字符串并需要对字符串化数组执行 JSON.parse() 以使其再次成为数组。 我不能在 componentDidMount 函数中这样做,因为在 Redux 中拥有状态组件不是最佳实践。我可以在渲染函数中做到这一点,但就我而言,在那里改变值并不是最佳实践。

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

那么如何在 Redux 的展示组件中管理 props 突变? 谢谢!

【问题讨论】:

  • 为什么不先在action中解析,然后再放到reducer中。那样只会发生一次。

标签: javascript reactjs redux react-redux mutation


【解决方案1】:

首先,我绝对不会在渲染函数中进行突变,因为它会被大量调用。 我的建议是阅读 ComponentDidMount 中的初始道具,您可以在其中相应地对其进行变异并将其存储在内部状态中。之后,如果值可能会发生变化,那么我建议在 ComponentWillReceiveProps 中执行相同的更改。 我也不认为改变给定的道具以使用它们是一种非常糟糕的做法。只需尝试将突变保持在最低限度,并将它们排除在渲染函数之外。

【讨论】:

    【解决方案2】:

    如果您使用的是 redux,我假设您已经在使用 mapStateToProps 函数,您可以在那里解析它并使其可用于 React 组件

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

    否则,您可以将 prop 保存为状态变量,因为您需要在 componentWillReceivePropscomponentWillMount/componentDidMount 生命周期函数中解析和设置状态,因为 componentWillMount 仅被调用一次,并且此后每次渲染都会调用 componentWillReceiveProps .

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-14
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      相关资源
      最近更新 更多