-
我有两个状态数组作为
processedData
和processedDataCopy
。我正在尝试将processedData
的副本存储在processedDataCopy
中。 -
processedDataCopy
不应反映对processedData
所做的任何更改,但一旦processedData
数据被更改,processedDataCopy
也会相应地更改以反映processedData
所做的更改。我应该如何防止它发生? -
我已经在
processedDataCopy
中使用setState
componentWillMount()
存储了processedData
的副本。 -
我的代码的简化版本是:
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)}) } }
也许这就是你需要的,https://www.npmjs.com/package/deepcopy
在这一行中
this.setState({processedDataCopy:this.state.processedData});
你把他们两个都连接起来了。 如果这样做:
let processedCopy = this.state.processedData.slice();
this.setState({processedDataCopy: processedCopy});
断开两个实体的连接,只需获取第一个实体的完整副本。