React native 在指定随机更改的对象值时作出本机反应

React native 在指定随机更改的对象值时作出本机反应,react-native,React Native,我正在将常量对象值指定给临时状态对象,在对临时对象进行更改的同时,常量对象值也在更改 我声明了一个常量对象值 const dict ={ '2019-07-10': [{text: 'Dr Eddie A Rosa'},{text: 'Dr Shahida N Siddiqui'}], '2019-07-11': [{text: 'Dr Dae W Lee'}], '2019-07-12': [{text: 'Dr Lisa F Brodkin'},{text:

我正在将常量对象值指定给临时状态对象,在对临时对象进行更改的同时,常量对象值也在更改

我声明了一个常量对象值

 const dict ={  
    '2019-07-10': [{text: 'Dr Eddie A Rosa'},{text: 'Dr Shahida N Siddiqui'}],  
    '2019-07-11': [{text: 'Dr Dae W Lee'}],
   '2019-07-12': [{text: 'Dr Lisa F Brodkin'},{text: 'Dr Eddie A Rosa'}]}
我的状态就像

export default class ScheduleCalendar extends Component {
 constructor(props) {
        super(props);
this.state = { tempdict:{}}
}
在函数调用中,我将const dict的值赋值给临时dict并操作临时dict

ondaypress =(date) => {
// Here date value is '2019-07-11'
        console.log('Inside the update markers of calendar.js new')


 this.setState({ tempdict: Object.assign({}, dict) }, () => 
{
 if(this.state.tempdict[date]) // Checking whether tempdict has the key date or not
        {
            this.state.tempdict[date].push({text:'Dr Beth' }) 
        }
        else{
          this.state.tempdict[date] = [{text:'Dr Beth'}]
        }
    })     
     }
    }
在这里,对象tempdict和dict都发生了变化,我们得到了输出

dict={
'2019-07-10': [{text: 'Dr Eddie A Rosa'},{text: 'Dr Shahida N Siddiqui'}],
'2019-07-11': [{text: 'Dr Dae W Lee'},{text:'Dr Beth'}],
'2019-07-12': [{text: 'Dr Lisa F Brodkin'},{text: 'Dr Eddie A Rosa'}]
}

tempdict ={
'2019-07-10': [{text: 'Dr Eddie A Rosa'},{text: 'Dr Shahida N Siddiqui'}],
'2019-07-11': [{text: 'Dr Dae W Lee'},{text:'Dr Beth'}],
'2019-07-12': [{text: 'Dr Lisa F Brodkin'},{text: 'Dr Eddie A Rosa'}]}
预计tempdict只应更改,dict不应更改

迪克特应该是这样的

dict ={
'2019-07-10': [{text: 'Dr Eddie A Rosa'},{text: 'Dr Shahida N Siddiqui'}],
'2019-07-11': [{text: 'Dr Dae W Lee'}],
'2019-07-12': [{text: 'Dr Lisa F Brodkin'},{text: 'Dr Eddie A Rosa'}]
}

我们也尝试过Object.freeze(),但得到的结果与将对象指定给状态时得到的结果相同,该状态也将存储对象引用,这就是为什么在状态中添加或删除任何内容时会影响所有引用对象的原因。 因此,在赋值之前,首先必须使用JSON.parseJSON.stringify转换对象

替换对象分配代码
对象。将({},dict)
分配为
Object.assign({},JSON.parse(JSON.stringify(dict))