【发布时间】:2023-04-09 11:06:01
【问题描述】:
一旦用户输入他们的姓名和电话号码,我就会尝试将用户信息发送到服务器。当用户输入他们的信息时,我能够获得正确的信息。但是,当我第一次运行该应用程序时,我得到了 this.state.name 和 this.state.phone 的空数据,而不是空字符串。
下面是我的代码:
constructor(){
super()
this.clearData = this.clearData.bind(this)
this.persistData = this.persistData.bind(this)
this.state = {
name: '',
phone: ''
}
}
submit(){
let collection = {}
collection.name = this.state.name,
collection.email = this.state.phone,
console.warn(collection)
var url = 'http://localhost:3000/users';
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(collection), // data can be `string` or {object}!
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
}
persistData(){
let name = this.state.name
let phone = this.state.phone
AsyncStorage.setItem('name', name)
AsyncStorage.setItem('phone', phone)
this.setState({ name: name, persistedName: name, phone: phone, persistedPhone: phone })
}
check(){
AsyncStorage.getItem('name').then((name) => {
this.setState({ name: name, persistedName: name })
})
AsyncStorage.getItem('phone').then((phone) => {
this.setState({ phone: phone, persistedPhone: phone })
})
}
componentWillMount(){
this.check()
}
render() {
////Here I am getting null!
console.log(this.state.name)
console.log(this.state.phone)
return ()
< View >
<TouchableOpacity
onPress={() => { this.persistData(); this.submit(); }}>
<Text> submit button </Text>
</TouchableOpacity>
</View >
}
当我第一次运行我的应用程序时,我想为 this.state.name 和 this.state.phone 获取空字符串。有什么办法可以做到这一点吗?
【问题讨论】:
标签: javascript reactjs react-native async-await