在将数据从“ componentWillReceiveProps”存储到AsyncStorage时遇到麻烦,我甚至不确定这是否可行?因为我已经在互联网上搜索了,实际上没有关于将“ componentWillReceiveProps”数据存储到AsyncStorage的帖子。
所以这就是我所得到的,“ componentWillReceiveProps”中的数据基本上来自其父组件/屏幕。从这里开始,当用户点击发送按钮时,我的“ componentWillReceiveProps”的数据应存储到AsyncStorage中,然后在需要显示时再次获取。
这是我的代码
ModalScreen.js
export default class ModalScreen extends Component {
constructor(props) {
super(props);
this.state = {
modalVisible: props.modalVisible,
textQty: '',
getDet: ''
getID_Det: ''
getPrice_Det: ''
};
}
componentWillReceiveProps(nextProps) {
this.setState({
modalVisible: nextProps.modalVisible,
OG_id: nextProps.id, // Data from other screen
OG_price: nextProps.price // this should be included in storing.
})
}
setItem = () => {
AsyncStorage.setItem('Key_1', this.state.textQty, this.state.OG_id, this.state.OG_price);
Alert.alert("Saved");
};
getItem = () => {
AsyncStorage.getItem('Key_1')
.then((value) => this.setState({ getDet : value }))
.then((value_1) => this.setState({ getID_Det : value_1 })) // I'm not sure if this is the right way.
.then((value_2) => this.setState({ getPrice_Det : value_2 }))
}
render() {
return (
<View>
<Modal
animationType = 'slide'
visible = { this.state.modalVisible }
onRequestClose={() => { this.props.setModalVisible(false) }}>
<View>
<View>
<Text>{this.state.OG_id}</Text>
<Text>{this.state.OG_price}</Text>
<TextInput
style={styles.textInput}
placeholder="Enter Quantity!"
onChangeText = { data => this.setState({ textQty : data }) }
returnKeyLabel = "done"
returnKeyType = "done"
/>
<TouchableOpacity onPress = { this.setItem }>
<Text>Send</Text>
</TouchableOpacity>
<TouchableOpacity
onPress = {() => { this.props.setModalVisible(false) }}>
<Text>Close</Text>
</TouchableOpacity>
<TouchableOpacity onPress = { this.getItem }>
<Text>Show</Text>
</TouchableOpacity>
<Text>{ this.state.getDet }</Text>
<Text>{ this.state.getID_Det }</Text>
<Text>{ this.state.getPrice_Det }</Text>
</View>
</View>
</Modal>
</View>
)
}
}
答案 0 :(得分:0)
我不确定这是否真的好,但是我通过创建专用于要存储在函数内部AsyncStorage中的其他项的其他键来解决此问题。
示例:
constructor(props) {
super(props);
this.state = {
Det_id: [],
Det_price: [],
textQty: '',
getDet: ''
}
}
setItem = () => {
AsyncStorage.setItem('Key_1', this.state.textQty);
AsyncStorage.setItem('Key_2',this.state.OG_id);
AsyncStorage.setItem('Key_3',this.state.OG_price);
Alert.alert("Saved");
};
getItem = () => {
AsyncStorage.getItem('Key_1')
.then((value) => this.setState({ getDet : value }));
AsyncStorage.getItem('Key_2')
.then((value_1) => this.setState({ getID_Det : value_1 }));
AsyncStorage.getItem('Key_3')
.then((value_2) => this.setState({ getPrice_Det : value_2 }));
}
注意:同样,我不确定这是否是正确的方法,但这是我的方法,如果你们碰巧知道一种更好的共享方法。 / p>