创建状态变量的常量副本

时间:2017-03-04 11:04:48

标签: react-native

  • 我有两个状态数组processedDataprocessedDataCopy。我正在尝试在processedData内存储processedDataCopy的副本。

  • processedDataCopy不应反映对processedData所做的任何更改,但只要processedData数据发生更改,processedDataCopy也会相应更改以反映processedData中所做的更改。我应该如何防止它发生?

  • 我已使用processedData内的processedDataCopysetState中存储了componentWillMount()的副本。

  • 我的代码的简化版本是:

    export default class ProductsPage extends Component {
    constructor(props) {
          super(props);
          var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
          this.state = {
            processedData:[],
            processedDataCopy:[],
            listData:ds.cloneWithRows([]),
          };
        }
    
    
      componentWillMount(){
        this.state.processedData.push({multipleKeysinloop:multipleValuesinLoop});
        this.setState({processedDataCopy:this.state.processedData})
        this.setState({listData:this.state.listData.cloneWithRows(this.state.processedData)})
      }
    
      render() {
        return (
          <ListView
           dataSource={this.state.listData}
           renderRow={this.printData.bind(this)}
           />
        );
      }
    
      printData(){
        //On some action load altered process data else reset to original processedData which is stored in processedDataCopy
        if(processedData is altered)
            this.setState({listData:this.state.listData.cloneWithRows(this.state.processedData)})
        else
            this.setState({listData:this.state.listData.cloneWithRows(this.state.processedDataCopy)})
      }
    
    }
    

2 个答案:

答案 0 :(得分:0)

也许这就是您所需要的,https://www.npmjs.com/package/deepcopy

答案 1 :(得分:0)

在此行

this.setState({processedDataCopy:this.state.processedData});

您已经将它们都连接了。 如果您这样做:

let processedCopy = this.state.processedData.slice();
this.setState({processedDataCopy: processedCopy});

您断开了两个实体的连接,只是获得了第一个实体的完整副本。