I stored an array in a.js file as i was going to use it in number of other files. Though i got it correctly in other files (checked by rendering the items of the array) but i am not able to mutate the array as i need to add and remove items from the array.
Here is the file where my array is present;
export default myArray = ['first thing', 'second thing', 'and so on'];
And this is what i tried;
First i imported it;
import myArray from 'path/of/the/file.js'
Then tried to mutate it;
myArray = [...myArray , andSomeOtherItem];
This shows an error;
myArray is read-only
After searching about it, i think that this is a default behavior of react-native. If i am right, then how can i achieve that?
That is because of it is readonly, myArray is just returning you the data, you cannot update or modify it,
what you can do is store copy in new array
userArray = myArray
userArray = [...userArray, 1];
the only way to change it will
export funciton myArrayfunction(val) {
myArray = ['first thing', 'second thing', 'and so on'];
if(val) {
myArray = [...myArray, val];
}
return myArray;
}
// then in your parent component
export default App() {
// pass the value you want to add in the array
myArrayFunction(someOtherValue)
}
if you want to do like that way you can try like below:
let myArray = require("./path/of/the/file.js");
myArray.default = [...myArray.default, "4"];
export default myArray.default;
This will also mutate your old array in the first file
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.