[英]How to update the value inside object in React native and Asyncstorage?
我是新來的反應本地人。 我使用 Asyncstorage 將數據存儲在 key = 'name' 中,並希望在元數據 object 中使用此值與購物車一起發送。 我無法更新 object 中的值。
我想將我的 Customtext 組件中的 textinput 值添加到“值”中:
僅供參考,function 位於 common 文件夾中,而 CustomText 位於 Components 文件夾中。
item.meta_data= [{
"key" : "custom_text",
"value" :
}]
這是組件代碼:
import React, { Component } from 'react';
import { Text, View, TextInput, StyleSheet } from 'react-native'
import AsyncStorage from "@react-native-community/async-storage";
import Tools from '../../common/Tools';
class CustomText extends Component {
constructor(){
super()
this.state = {
'name': ''
}
}
componentDidMount = () => AsyncStorage.getItem('name').then((value) => this.setState({ 'name': value }))
setName = (value) => {
AsyncStorage.setItem('name', value);
this.setState({ 'name': value });
// console.log(value);
// DefaultPreference.set('name', value).then(function() {alert('done')});
}
render() {
return (
<View style = {styles.container}>
<Text style={{
top:-250,
left: 8,
fontWeight:'bold' }}>
{this.state.name}
</Text>
<TextInput
style={styles.nameInput}
autoCapitalize = 'none'
onChangeText = {this.setName}
/>
</View>
)
}
}
export default CustomText
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'transparent',
alignItems: 'center',
justifyContent: 'center'
},
title: {
fontSize: 8,
marginBottom: 10,
marginTop: 6,
color: 'white'
},
nameInput: {
fontSize: 14,
marginBottom: 12,
borderWidth: 1,
padding: 12,
width: '80%',
borderRadius: 10,
backgroundColor: 'white'
},
image: {
width: 10,
height: 20,
borderColor: 'orange',
borderWidth: 2,
borderRadius: 100,
}
});
這是 function 我想在其中更新值
static getItemsToCheckout = (cartItems) => {
const items = [];
for (let i = 0; i < cartItems.length; i++) {
const cartItem = cartItems[i];
const item = {
product_id: cartItem.product.id,
quantity: cartItem.quantity,
};
if (cartItem.variation !== null) {
item.variation_id = cartItem.variation.id;
}
item.meta_data=[
{
"key" : "custom_text",
"value" : **WANT TO UPDATE HERE**
}
]
items.push(item);
}
return items;
};
}
嘗試這個:
setName = (value) => {
let newValue = this.state.name;
newValue.custom_text = value;
AsyncStorage.setItem('name', newValue);
this.setState({ 'name': newValue });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.