简体   繁体   中英

Can not add property 2, object is not extensible Array.push

I'm trying to add an array to a global array. Then save that array to AsyncStorage . But I can't seem to be able to do that and I'm not sure why.

It seems to have a problem with pushing to that array.

I have tried pushing any key to it, but still that didn't fix my problem.

//for saving all transactions

let exchanges =[ x = ''];
class AddScreen extends React.Component {

constructor(props) {
i=0;
super(props);

this.state = {text: '',  name:'',amount:'',budget:'',date:'',geoloc:''};
}

setName = () => {
const {text} = this.state;
AsyncStorage.setItem('name', text);
alert("data Saved " +text);
}

SavetoGlobalTransaction = () => {
//get everything from state
const {name} = this.state;
const {amount} = this.state;
const {budget}= this.state;
const {date}= this.state;
const {geoloc}= this.state;

trans = {
  name :this.name,amount:this.amount,budget:this.budget,date:this.date,geoloc:this.geoloc
}

exchanges.push(trans);

AsyncStorage.setItem('ex', exchanges);
alert("data Saved " +exchanges[0].name);
}

This is the kind of error that I get:

Cannot add property 2, object is not extensible
    Array.push
     <anonymous>
    Object.AddScreen._this.SavetoGlobalTransaction [as onPress]
     f6f1eeda-c1a7-4b01-ba0e-76dc313c6ebd:2177:19
    Object.touchableHandlePress
     f6f1eeda-c1a7-4b01-ba0e-76dc313c6ebd:15410:40
    Object._performSideEffectsForTransition
     f6f1eeda-c1a7-4b01-ba0e-76dc313c6ebd:14990:16
    Object._receiveSignal
     f6f1eeda-c1a7-4b01-ba0e-76dc313c6ebd:14916:14
    Object.touchableHandleResponderRelease
     f6f1eeda-c1a7-4b01-ba0e-76dc313c6ebd:14795:12
    Object.invokeGuardedCallbackImpl
     f6f1eeda-c1a7-4b01-ba0e-76dc313c6ebd:27408:16
    invokeGuardedCallback
     f6f1eeda-c1a7-4b01-ba0e-76dc313c6ebd:27499:37
    invokeGuardedCallbackAndCatchFirstError
     f6f1eeda-c1a7-4b01-ba0e-76dc313c6ebd:27503:31
    executeDispatch
     f6f1eeda-c1a7-4b01-ba0e-76dc313c6ebd:27697:9

You cannot modify the array, you need to create a new array with the additional data and save that. Try using .concat or the spread operator.

I would recommend to just use spread operator(...) and it will just bomb the values of your trans object and add it into the exchange array

exchanges.push(...trans);

This should do the work.

I have hit the same error as yours. My way to resolve this is to deep clone the original array to a new one and then operate the new array and use the new array as the data source.

As for your code, you can deep clone the AsyncStorage and use the new array to insert your previous array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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