App 函数不返回任何来自 React Native 中的异步操作的内容



我是 React Native 的新手,这是我写的第一段代码。我不确定当我的 App(( 封闭函数中有异步操作时如何从它返回我的 jsx。 我怀疑这是一个非常基本的错误,所以希望我的代码能清楚地显示问题:

import React from 'react';
import { Text, View, TextInput, Button, Alert } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
//check if logged in, if not show login screen
export default function App() {
AsyncStorage.getItem("user")
.then((user) => {
if(user) {
//user validated
return (
<View>
<Text>Logged In!</Text>
</View>
);

} else {
//user not logged in, therefore show login screen
return (
<View>
<Text>Enter Your Username</Text>
<TextInput 
maxLength={16} 
/>
<Button 
title="Login"
/>
</View>
);
}
});
}

外部 App(( 函数显然没有返回任何内容,但我不确定如何让它等待并从内部异步函数返回 jsx。

尝试过:我最初在外部函数和AsyncStorage.getItem(...)上使用 async/await ,但这返回了以下错误:Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

接下来,在SO阅读了类似问题的答案后,我尝试了另一种方法:

export default function App() {
return (
<View>
<Login />
</View>
);
async function Login() {
const user = await AsyncStorage.getItem("user");
if(user) {
return (
<Text>Logged In!</Text>
);
} else {
return (
<Text>Enter Your Username</Text>
);
}
}
}

但是当我使用 async/await 时,我遇到了与上述相同的错误。

我是 React Native 的新手,所以请用"傻瓜"的解释来打我。

正如我在评论中所说,因为你的JSX被包装在一个承诺中(因为异步函数总是返回一个承诺(,React说Objects are not valid as a React child

可以使用useStateuseEffect挂钩来维护用户状态并获取用户。例如:

function Login() {
const [user, setUser] = useState();
useEffect(() => {
if(!user) {
AsyncStorage.getItem('user')
.then(user => setUser(user));
// .catch()
}
}, [user, setUser]) // also add any other required dependencies
if(user) {
return (
<Text>Logged In!</Text>
);
} else {
return (
<Text>Enter Your Username</Text>
);
}
}

我更喜欢类组件,因此,我会这样做: 导出默认类 应用扩展组件 {

constructor(props) {
super(props)
this.state = {
user: null //intialize a user state with null
}
}
componentDidMount = () => {
const user = await AsyncStorage.getItem("user");//get the user on component mount and set state to user
this.setState({ user }) // this.setState({ user: user }) does same
}
render() {
const { user } = this.state; //destructure state here
return (
<>
<View>
<Login />
</View>
{
user ? //if user show logged in else show enter username
<Text>Logged In!</Text> :
<Text>Enter Your Username</Text>
}
</>
)
}

}

最新更新