首页 > 解决方案 > 使用路径的 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>
    )
}

标签: javascriptreactjsreact-router

解决方案


没有一个工作示例很难确定,但如果它在稍微延迟后工作,听起来就像是从服务器加载图像(如,图像尚未下载,所以你需要等待从服务器下载图像)。初始加载图像后是否有延迟?换句话说,第一次显示图像后延迟是否仍然存在?

如果是这样,您可以在获取列表后尝试预加载图像。这样它们就已经加载到客户端并且可以立即渲染。

希望有帮助。


推荐阅读