gpt4 book ai didi

javascript - 值未在 then 语句内分配

转载 作者:行者123 更新时间:2023-11-28 16:47:04 24 4
gpt4 key购买 nike

在这个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;

最佳答案

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

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} />
}

关于javascript - 值未在 then 语句内分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60401119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com