我正在寻找一种使用 react-testing-library 测试 React.Suspense 回退的方法。考虑这个例子:
const MyLazyThing = lazy(() => import('./index'));
export default function MyThing(props) {
return (
<Suspense fallback="loading...">
<MyLazyThing {...props} />
</Suspense>
);
}
Run Code Online (Sandbox Code Playgroud)
使用getByText('loading...')似乎不起作用。想知道是否有一种在 RTL 中进行测试的好方法。
谢谢
这是我的懒惰组件:
const LazyBones = React.lazy(() => import('@graveyard/Bones')
.then(module => ({default: module.BonesComponent}))
export default LazyBones
Run Code Online (Sandbox Code Playgroud)
我是这样导入的:
import Bones from './LazyBones'
export default () => (
<Suspense fallback={<p>Loading bones</p>}>
<Bones />
</Suspense>
)
Run Code Online (Sandbox Code Playgroud)
在我的测试中,我有这样的事情:
import * as LazyBones from './LazyBones';
describe('<BoneYard />', function() {
let Bones;
let wrapper;
beforeEach(function() {
Bones = sinon.stub(LazyBones, 'default');
Bones.returns(() => (<div />));
wrapper = shallow(<BoneYard />);
});
afterEach(function() {
Bones.restore();
});
it('renders bones', function() {
console.log(wrapper)
expect(wrapper.exists(Bones)).to.equal(true);
})
})
Run Code Online (Sandbox Code Playgroud)
我期望的是测试通过,并且 console.log 打印出来:
<Suspense fallback={{...}}>
<Bones /> …Run Code Online (Sandbox Code Playgroud) 我想在Powers获取/未定义时渲染后备组件。React.Suspense我使用代码在我的逻辑中实现:
<Suspense fallback={<p>Loading</p>}>
<RoutesPowers />
</Suspense>
Run Code Online (Sandbox Code Playgroud)
我的RoutesPowers是
const Powers = [ ... ];
const RoutesPowers = () => {
const [powers, setPowers] = useState(null);
const fetchPowers = () => setTimeout(() => setPowers(Powers), 3000);
useEffect(() => fetchPowers(), []);
return ( powers.map(route => <RoutePowers route={route}/> )
};
Run Code Online (Sandbox Code Playgroud)
但它给了我Cannot read property "map" of null可能是因为powers是空的。这意味着它React.Suspense没有发挥应有的作用。有人能帮我解决这个问题吗?
我有一个像这样结构的组件,并ErrorBoundary包装了我的Suspense元素。
function App() {
return (
<ErrorBoundary fallback={<h2>Could not fetch cities.</h2>}>
<Suspense fallback={<div>Loading..</div>}>
<MyList />
</Suspense>
</ErrorBoundary>
);
}
Run Code Online (Sandbox Code Playgroud)
该MyList组件包含一个SWR数据获取钩子,如下所示:
const { data } = useSwr(`/api/mydata`, fetcher, {
suspense: true,
});
Run Code Online (Sandbox Code Playgroud)
我的 fetcher 方法抛出错误,如下所示:
const rsp = await fetch(url);
if (rsp.ok) {
return await rsp.json();
} else {
const MyError = function (message, status) {
this.message = `${message} from url ${url} status code:${status}`;
this.status = status;
};
throw new MyError(rsp.statusText, rsp.status);
} …Run Code Online (Sandbox Code Playgroud) 我用谷歌搜索,观看了很多视频来实现类似 YouTube 加载的功能,如下面的屏幕截图所示。因此,我有基于路线的导航,其中有延迟加载,因此一切正常,但在加载内容时,反应悬念将使组件显示:无,因此它在屏幕上变得不可见,只有后备组件可见
我想让内容保持可见,我将制作一个自定义后备组件,例如 YouTube。
<Suspense fallback={<div>Loading...</div>}>
{content}
</Suspense>
Run Code Online (Sandbox Code Playgroud)
使用 @loadable/server 中的 ChunkExtractor,我们可以在页面正文中包含链接,以在 SSR 期间预加载必要的块。
通过将这些脚本与 HTML 文档之后的主块同时加载,可以加快水合速度。
我怎样才能在没有 @loadable 的情况下使用 React 18 SSR + Lazy/Suspense 做同样的事情?
renderToPipeableStream 的onAllReady回调没有参数。
I am trying to implement i18next in my react component using the useTranslation hook, but it keeps saying:
Uncaught Error: Test suspended while rendering, but no fallback UI was specified.
Add a
<Suspense fallback=...>component higher in the tree to provide a loading indicator or placeholder to display.
我怎样才能添加<Suspense>比我拥有的更高的任何东西?我究竟做错了什么?我该如何解决?当我使用该<Translation>组件时,它似乎工作正常。当然,如果我关闭 Suspense 并尝试自己处理它似乎也可以正常工作,但我认为这违背了目的。我怎样才能使它真正起作用?我的 Fetch 后端是否配置错误?
import React, { Suspense, useState, useEffect, lazy } from "react";
import PropTypes from "prop-types";
import i18n from './i18n';
import { useTranslation } …Run Code Online (Sandbox Code Playgroud) 我有一个简单的主从场景,在左侧,我使用useSwrREST 服务加载城市列表,然后在右侧,我有一个城市详细信息窗口,也用于useSwr加载单个城市(通过单击左,或第一次加载)。
useSwr在下面的代码中,我调用 useEffect 函数,然后使用从状态设置调用 (setSelectedCityId) 中检索的数据。
这是可行的,并且始终存在与城市数组相关的数据,但我想知道是否可以保证 useEffect 的函数将在 Suspense Promise 完成后运行(就像看起来那样)。
这是我的简单代码:
import { Suspense, useEffect, useState, useTransition } from "react";
import useSwr from "swr";
const fetcher = (...args) => fetch(...args).then((res) => res.json());
function CityDetailFallback() {
return <div>Loading (CityDetail)</div>;
}
function CityDetail({ selectedCityId }) {
function CityDetailUI({ selectedCityId }) {
const { data: city } = useSwr(
selectedCityId
? `http://localhost:3000/api/city/${selectedCityId}`
: null,
fetcher,
{
suspense: true,
}
);
if (!city) {
return <div>loading …Run Code Online (Sandbox Code Playgroud) 我正在尝试将纹理用于我的 ThreeJS 对象。我收到错误:
index.js:1 Error: Earth suspended while rendering, but no fallback UI was specified.
Add a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display.
in Earth
Run Code Online (Sandbox Code Playgroud)
地球.js:
export const Earth = () => {
const texture = useLoader(THREE.TextureLoader, earthImg)
return (
<Suspense fallback={<h1>Loading profile...</h1>}>
<mesh>
<sphereBufferGeometry attach="geometry" args={[5, 32, 32]} />
<meshStandardMaterial attach="material" roughness={1} fog={false} />
</mesh>
</Suspense>
)
}
Run Code Online (Sandbox Code Playgroud)
索引.js:
export default function App() {
return (
<Canvas
style={{height:'100vh',width:'100vw'}}
camera={{ …Run Code Online (Sandbox Code Playgroud) 通常,当我返回依赖于获取的数据的组件(我使用 nextjs 13)时,我有条件地渲染元素以确保值可用:
表组件:
export const Table = ({ ...props }) => {
const [tableEvents, setTableEvents] = useState(null);
useEffect(() => {
fetchAndSetTableEvents();
}, []);
async function fetchAndSetTableEvents() {
const fetchedEvents = await fetch(* url and params here *)
if (fetchedEvents && fetchedEvents) {
setTableEvents(fetchedEvents);
} else {
setTableEvents(null);
}
}
return (
<React.Fragment>
<div>
{tableEvents ? tableEvents[0].title : null}
</div>
</React.Fragment>
)
};
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用Suspense从父组件加载 TableComponent ,它会加载但不会在加载之前显示回退:
<Suspense fallback={<div>Loading Message...</div>}>
<TableComponent />
</Suspense>
Run Code Online (Sandbox Code Playgroud)
但是,如果我删除TableComponent中的条件渲染并仅指定变量,则在尝试加载组件时回退会正确显示:
return (
<React.Fragment>
<div>
{tableEvents[0].title} …Run Code Online (Sandbox Code Playgroud) react-suspense ×10
reactjs ×9
javascript ×3
swr ×2
async-await ×1
fallback ×1
lazy-loading ×1
next.js ×1
react-18 ×1
react-hooks ×1
sinon ×1