繁体   English   中英

从 react-native 中的 another.js 文件中改变 one.js 文件中存在的数组

[英]Mutating an array present in one .js file from another .js file in react-native

我将一个数组存储在 a.js 文件中,因为我将在许多其他文件中使用它。 虽然我在其他文件中正确地得到了它(通过渲染数组的项目来检查),但我无法改变数组,因为我需要从数组中添加和删除项目。

这是我的数组所在的文件;

export default myArray = ['first thing', 'second thing', 'and so on'];

这就是我尝试过的;

首先我导入了它;

import myArray from 'path/of/the/file.js'

然后尝试对其进行变异;

myArray = [...myArray , andSomeOtherItem];

这显示了一个错误;

myArray is read-only

经过搜索,我认为这是 react-native 的默认行为。 如果我是对的,那么我该如何实现呢?

那是因为它是只读的,myArray 只是返回数据,你不能更新或修改它,

您可以做的是将副本存储在新数组中

userArray = myArray
userArray = [...userArray, 1];

改变它的唯一方法是

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)

}


如果你想这样做,你可以尝试如下:

let myArray = require("./path/of/the/file.js");

myArray.default = [...myArray.default, "4"];

export default myArray.default;

这也会改变第一个文件中的旧数组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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