动态反应路径路由与url不匹配,但在重新加载时匹配



。我正试图使用动态路由和React Link标记移动到一个url。问题是它更改了url,但没有重新呈现ui。当我使用锚点标记或刷新页面时,它会进行渲染。我一直在尝试检测这个问题,但目前我被卡住了。我在下面实施了一些类似的方法,效果很好。

这是我的App.js 的一个片段

// Front end pages
if (isFrontEndPage()) {
return (
<Layout className="app-container">
<AppHeader />
<Layout>
<AppSidebar />
<Content className="app-content" breakpoint="lg">
<div className="container" style={{ minHeight: '100vh', padding: '10px' }} >
<Switch>   
<Route path="/" exact component={Home} />
<Route path="/pricing" exact component={Pricing} />
<Route path="/features" exact component={Features} />
<Route path="/help/search/result.html" exact component={Post} />
<Route path="/help" exact render={(props) => <Redirect to="/p/help/invoices/index.html" /> } />
// I have a problem with this
<Route path="/p/:postType/:postCategoryUrlTitle/:postUrlTitle.html" component={Post} />
// I also have a problem with this
<Route path="/:postUrlTitle" component={Post} />

<Route component={NotFound} />
</Switch>
</div>
</Content>
</Layout>
<AppFooter />
</Layout>
)
}
return (
<Layout className="app-container">
<AppHeader />
<Layout>
<AppSidebar />
<Content className="app-content" breakpoint="lg">
<div className="container" style={{ minHeight: '100vh', padding: '10px' }} >
<Switch>   
// The below similar links actually render accurately with dynamic routing
<PrivateRoute path="/posts/info-posts/new" component={InfoPost} />
<PrivateRoute path="/posts/info-posts/info-post/:infoPostId" component={InfoPost} />
<PrivateRoute path="/posts/info-posts" component={InfoPosts} />

<**************** OTHER PATHS ***********************>
<PrivateRoute component={NotFound} />
</Switch>
</div>
</Content>
</Layout>
<AppFooter />
</Layout>
);
}
export default App;

下面是我的Index.js 的一个片段

............
ReactDOM.render(
<BrowserRouter>
<AuthProvider>
<App />
</AuthProvider>
</BrowserRouter>,
document.getElementById('root')
);

使用React的Link组件时,页面不会刷新,只会切换组件/视图,这就是Link的工作方式。如果使用锚点标记,则页面将刷新。不确定你的应用程序中到底发生了什么,但从我所看到的,我注意到你正在为更多的路线链接相同的组件,也许这就是为什么你的UI不会改变的原因

最终解决了问题。由于我已经在我想要路由到的组件中,所以当检测到"useRouteMatch"的params属性发生更改时,我所需要做的就是使用React钩子"useRouteMatch"再次使用"useEffect"实际渲染组件。

...
const {postType, postCategoryUrlTitle, postUrlTitle } = useRouteMatch().params;
...
useEffect(() => {
// Now do stuff with the params
}, [postType, postCategoryUrlTitle, postUrlTitle]);

最新更新