首页 > 解决方案 > 值没有在 then 语句中赋值

问题描述

在这个 js 文件中,我定义了这个 const Device,它是正在使用的移动设备的名称。问题是当我从另一个 js 调用 Device 时,它​​返回为空。为什么?

import DeviceInfo from 'react-native-device-info';

var Device = ''

DeviceInfo.getDeviceName().then(deviceName => {
  Device = deviceName + ' ('+DeviceInfo.getSystemVersion()+')'
});

export default Device;

标签: javascriptreactjsreact-native

解决方案


您当前的方法不起作用的原因是因为DeviceInfo.getDeviceName是一个异步调用,它返回一个PromisedeviceName.

var Device = ''

DeviceInfo.getDeviceName().then(...)

// the call above will not wait before it goes to next line
// so `Device` will stay as empty string and will be exported as such

export default Device

相反,如果你想在多个地方重用这个逻辑,我建议把它变成一个函数,就像下面的例子:

import DeviceInfo from 'react-native-device-info';

function getDeviceFullName() {
  return DeviceInfo.getDeviceName()
    .then(deviceName => {
      return `${deviceName} (${DeviceInfo.getSystemVersion()})`
    })
}
export default getDeviceFullName

然后,您可以在其他地方调用此函数,如下例所示:

import getDeviceFullName from './getDeviceFullName'

class App extends React.Component {
  state = {deviceName: ""}

  componentDidMount() {
    getDeviceFullName()
      .then(deviceName => {
        this.setState({ deviceName })
      })
      .catch(/* handle errors appropriately */)
  }

  render() {
    return this.state.deviceName === "" 
      ? "Loading" 
      : this.state.deviceName;
  }
}

编辑作为 OP 提到了一些关于Formik集成的事情。

尚未对此进行测试,但我的方法如下。

class MyReactNativeForm extends React.Component {
  state = {
    initialValues: { email: "johndoe@gmail.com", deviceName: "" }
  }

  componentDidMount() {
    getDeviceFullName()
      .then(deviceName => {
        this.setState(prevState => {
          return {
            initialValues: {...prevState.initialValues, deviceName}
          }
        })
      })
      .catch(/* handle errors appropriately*/)
  }

  render() {
    return this.state.initialValues.deviceName === ""
      ? "Loading"
      : <Formik initialValues={this.state.initialValues} />
}

推荐阅读