javascript - 值没有在 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;
解决方案
您当前的方法不起作用的原因是因为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} />
}
推荐阅读
- ruby-on-rails - 为什么资产:Rails 6.1 上的预编译失败?
- php - 如何显示 3 栏新闻布局
- sharepoint - Sharepoint 选择字段验证不起作用?
- ansible - ansible 脚本模块:`cmd` 是做什么用的?
- python - 如何“注入”cookie
- python-3.x - excel文件不会通过python传输到sqlite
- python - 估计跨多列的每一行的线性趋势,以便预测下一个值
- linux - 使用 terraform/Linux 在 OCI 上部署资源
- react-native - Redux 坚持不同步
- c# - 如何仅为单击 MVC C# 中的按钮或 ActionLink 的用户“预订”并在另一个视图中显示其他用户的帖子?