【问题标题】:react native async getting null when running first time第一次运行时反应原生异步为空
【发布时间】:2023-04-09 11:06:01
【问题描述】:

一旦用户输入他们的姓名和电话号码,我就会尝试将用户信息发送到服务器。当用户输入他们的信息时,我能够获得正确的信息。但是,当我第一次运行该应用程序时,我得到了 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】:

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

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

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

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

    【讨论】:

    • 非常感谢!第一个不会用空字符串替换 null 但你给我的第二个选项效果很好!
    猜你喜欢
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 2021-12-07
    • 2020-12-26
    • 1970-01-01
    • 2020-05-10
    • 2020-07-09
    • 2016-10-16
    相关资源
    最近更新 更多