【发布时间】:2021-05-04 11:30:44
【问题描述】:
我是原生反应的新手。我使用 Asyncstorage 将数据存储在 key = 'name' 中,并希望在元数据对象中使用此值与购物车一起发送。我无法更新对象内的值。
我想将我的 Customtext 组件中的 textinput 值添加到“值”:in
仅供参考,该函数位于 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,
}
});
这是我要更新值的函数
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;
};
}
【问题讨论】:
-
请不要全部大写。
-
感谢 James Z...会记住这一点
标签: javascript arrays react-native object asyncstorage