第一次运行时,本机异步会变为null

问题描述 投票:0回答:1

我试图在用户输入他们的姓名和电话号码后将用户信息发送到服务器。当用户输入他们的信息时,我能够获得正确的信息。但是,当我第一次运行应用程序时,我得到this.state.namethis.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.namethis.state.phone获取空字符串。有没有办法可以做到这一点?

javascript reactjs react-native async-await
1个回答
1
投票

AsyncStorage如果尚未设置,则返回null值。所以在你的情况下,当你第一次运行应用程序并调用this.check()时,返回的值是null。您的回调会覆盖默认状态。按下提交后,它会被设置为下次运行应用程序时设置它。

您需要在AsyncStorage回调中设置默认值:

this.setState({name: name || '', persistedName: name || ''})

如果它是!= null并且未定义,则设置名称,否则它设置空字符串。

© www.soinside.com 2019 - 2024. All rights reserved.