React Native:悬念不呈现回退视图



我使用react native cli创建了一个空项目。以下是版本:

"react": "18.2.0",
"react-native": "0.71.6"

App.tsx文件:

import type {PropsWithChildren} from 'react';
import React, {Suspense} from 'react';
import {Text, View} from 'react-native';
type SectionProps = PropsWithChildren<{
title: string;
}>;
const MyComponent = React.lazy(() => import('./Component'));
function App() {
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Text>Hello!</Text>
<Suspense
fallback={
<View>
<Text>Loading...</Text>
<Text>Loading...</Text>
<Text>Loading...</Text>
<Text>Loading...</Text>
</View>
}>
<MyComponent />
</Suspense>
</View>
);
}
export default App;

下面是Component.tsx的内容:

import React, { useEffect, useState } from "react";
import { Text, View } from "react-native";
function loadData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("loaded data");
}, 8000);
});
}
export default function MyComponent() {
const [data, setData] = useState<string>("");
useEffect(() => {
loadData().then((data) => {
setData("This is test!!!");
});
}, []);
return (
<View>
<Text>{data}</Text>
</View>
);
}

我使用React.lazy()加载组件,然后使用Suspense在承诺解决后立即渲染组件。我期望React在渲染MyComponent之前渲染回退视图,但它似乎没有这样做!

我错过了什么?

这里的问题是你的组件没有花足够的时间来渲染回退,你只是延迟了它内部的数据加载,而不是组件本身。

如果你想显示回退,你必须延迟组件本身的加载,见下面的例子:

const MyComponent = React.lazy(() => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(import("./Component"));
}, 3000);
});
});

最新更新