javascript - 使用路径的 params.name 在数组中查找索引在更改路径后延迟
问题描述
我有一系列项目。每个项目包含多个图像。通过遍历这个数组,我显示了每个名字。我Link
为每个项目导航分配到包含项目名称的路径。我的意图是获取此名称,然后显示单击项目的图像。
项目页面还包含下一个项目按钮 - 单击此按钮将更改路径。这就是我获得新项目的方式:
cart;
nextCart;
componentDidUpdate(prevProps, prevState, snapshot) {
const prevPathname = prevProps.location.pathname;
const pathname = this.props.location.pathname;
if (pathname !== prevPathname) {
this.getCarts();
}
}
getCarts = () => {
const name = this.props.match.params.name;
this.cart = this.props.carts.find(value => value.name === name);
const currentIndex = this.props.carts.findIndex(value => value.name === name);
const nextIndex = currentIndex < this.props.carts.length - 1 ? currentIndex + 1 : 0;
this.nextCart = this.props.carts[nextIndex];
};
问题是,即使图像发生变化,它也会在更改路径后短暂延迟后发生。有没有更好的方法来实现这种行为?
换句话说,当我单击按钮更改路径时,会延迟到旧项目的图像消失并被新项目替换。
我如何更改路径:
this.props.history.push('/project/' + this.nextCart.name);
应用程序.js
function App() {
...
return (
<div className="App">
<Router history={history}>
<ScrollToTop>
<Header/>
{projects ?
<div>
<Route path="/project/:name" component={() => <Project carts={projects}/>}/>
<Route path="/about" component={About}/>
<div className="hs">
<Route path={["/", "/project/:name"]} exact
component={() => <CartHolder carts={projects}/>}/>
</div>
<div className="hs-mobile">
<Route path="/" exact component={() => <CartHolderMobile carts={projects}/>}/>
</div>
</div>
: <div className="black-overlay"/>}
</ScrollToTop>
</Router>
</div>
)
}
解决方案
没有一个工作示例很难确定,但如果它在稍微延迟后工作,听起来就像是从服务器加载图像(如,图像尚未下载,所以你需要等待从服务器下载图像)。初始加载图像后是否有延迟?换句话说,第一次显示图像后延迟是否仍然存在?
如果是这样,您可以在获取列表后尝试预加载图像。这样它们就已经加载到客户端并且可以立即渲染。
希望有帮助。
推荐阅读
- docker - 在 docker run 命令中传递参数
- javascript - 如何设置 SVG 图像的样式以延迟更改颜色
- python - 在一个非常大的列表中查找一个元组
- azure-devops - Azure DevOps 管道运行缓慢
- python-3.x - Python,列表和字符串变量的范围实际上不同吗?
- sql - Linq MVC5 MSQL 从包含大量列的表中选择一些列,以便更好更快地查询
- javascript - 访问打字稿中的对象并找到它的最高键和值
- android - 如何为 Android Jetpack Compose Column 或 Row 添加淡入淡出的边缘效果?
- okta - 奥克塔。将组分配给应用程序时如何禁用组属性表单?
- python - 如何从工作计算机安装 Plotly(使用 Anacando 或 PIP)