![](/img/trans.png)
[英]Uncaught TypeError: Cannot add property 0, object is not extensible at Array.push
[英]Can not add property 2, object is not extensible Array.push
我正在嘗試將數組添加到全局數組。 然后將該數組保存到AsyncStorage
。 但我似乎無法做到這一點,我不知道為什么。
推送到該數組似乎有問題。
我試過按任何鍵,但這仍然沒有解決我的問題。
//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);
}
這是我得到的那種錯誤:
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
您不能修改數組,您需要使用附加數據創建一個新數組並保存。 嘗試使用 .concat 或擴展運算符。
我建議只使用擴展運算符(...),它只會轟炸您的 trans 對象的值並將其添加到交換數組中
exchanges.push(...trans);
這應該可以完成工作。
我遇到了和你一樣的錯誤。 我解決這個問題的方法是將原始數組深度克隆為一個新數組,然后操作新數組並使用新數組作為數據源。
至於你的代碼,你可以深度克隆AsyncStorage
並使用新數組插入你以前的數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.