简体   繁体   中英

In React Native i have “WARN Possible Unhandled Promise Rejection (id: 5): TypeError: array.push is not a function”

I ask help for React Native. I have this code:

let historicalCaliberNumCm = await AsyncStorage.getItem('@historicalCaliberNum');
console.log(historicalCaliberNumCm);
console.log(this.state.cm);
historicalCaliberNumCm.push(this.state.cm);

This is the result:

[Tue Jan 05 2021 23:48:50.330]  LOG      [0.992872416250891]
[Tue Jan 05 2021 23:48:50.332]  LOG      0.3682160866743222
[Tue Jan 05 2021 23:48:50.461]  WARN     Possible Unhandled Promise Rejection (id: 5):
TypeError: _historicalCaliberNumCm2.push is not a function. (In '_historicalCaliberNumCm2.push(_this2.state.cm)', '_historicalCaliberNumCm2.push' is undefined)

Can anyone help me?

AsyncStorage.getItem returns a string, not an array, hence you can't use .push() which is a function for an array. You should use, eg JSON.parse(historicalCaliberNumCm); first to convert that string into an array.

AsyncStorage stores strings only. Please check docs: https://reactnative.dev/docs/asyncstorage

There's no guarantee that item under specified key exists. You should check if it's not null first. Then if it's not, you have to parse string into an object. For example you can use JSON.parse(historicalCaliberNumCm) . Then if result is an array, you can push into it additional data.

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