【发布时间】:2018-06-25 15:52:04
【问题描述】:
我在将数据从“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>
)
}
}
【问题讨论】:
-
可以在componentDidMount lifcycle函数中试试吗?
标签: javascript android react-native asynchronous