简体   繁体   English

在Redux / React组件中更改props值的正确方法是什么?

[英]What's the correct way to mutate props value in Redux/React components?

I have an array that comes as an String (and cannot change it for now). 我有一个字符串形式的数组(目前无法更改)。 I receive the String and need to do JSON.parse() over stringified array, to make it an array again. 我收到了String,并且需要对字符串化数组执行JSON.parse(),以使其再次成为数组。 I cannot do it in componentDidMount function, because it's not a best practice to have state component in Redux. 我不能在componentDidMount函数中执行此操作,因为在Redux中具有状态组件不是最佳实践。 I could do it in the render function, but as far I'm concerned it's not also a best practice to mutate values there. 我可以在render函数中做到这一点,但到目前为止,我担心这不是在其中进行值突变的最佳实践。

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

So how can I manage props mutation in Redux's presentational component? 那么如何在Redux的演示组件中管理道具突变呢? Thanks! 谢谢!

If you are using redux, I am assuming you would already be using a mapStateToProps function, you can parse it there and make it available to the React component 如果您使用的是redux,我假设您已经在使用mapStateToProps函数,则可以在那里解析它并将其提供给React组件

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

}

Otherwise you can save the prop as a state variable, for that you need to parse and setState in componentWillReceiveProps and componentWillMount/componentDidMount lifecycle functions since componentWillMount is only called once and componentWillReceiveProps is called on every render thereafter. 否则,您可以将prop保存为状态变量,因为您需要在componentWillReceivePropscomponentWillMount/componentDidMount生命周期函数中进行解析和setState,因为componentWillMount仅被调用一次, componentWillReceiveProps在之后的每个渲染都被调用。

First of I would definitely not do the mutation in the render function, since it will be called a lot. 首先,我肯定不会在render函数中进行突变,因为它将被称为很多。 What I would suggest is read the initial props in ComponentDidMount where you mutate them accordingly and store it in the internal state. 我建议阅读ComponentDidMount中的初始道具,在其中相应地对其进行突变并将其存储在内部状态中。 After that, if the value might change, then I would recommend doing the same mutation in ComponentWillReceiveProps. 此后,如果值可能更改,那么我建议在ComponentWillReceiveProps中进行相同的更改。 I also don't believe that it is a very bad practice to mutate the given props to use them. 我也不相信改变给定道具来使用它们是非常不好的做法。 Just try to keep the mutations to a minimum and keep them out of the render function. 只是尝试将变异保持在最低水平,并将其排除在渲染函数之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM