tap*_*ave 5 router reactjs react-router react-redux react-router-redux
当我从 /home 导航到 /dashboard 时,路由器工作正常,但是当我从 /home 导航到 /profile:id 时,路由器将我导航到也工作正常的配置文件页面,但是当我刷新它时,它会变成空白页面并且没有给我任何 404 或重定向回主页,我正在使用
react-router: "^4.2.0",
react-router-dom: "^4.2.2",
react-router-redux: "5.0.0-alpha.6",
那么,如何摆脱空白页面,如果 url 位于 /profile/5,然后在刷新页面上导航回主页或任何适当的内容,请帮忙?
索引.js
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<Switch>
<Route path="/" component={App} />
<Route component={Page404} />
</Switch>
</ConnectedRouter>
</Provider>,
document.getElementById('app-site')
);
Run Code Online (Sandbox Code Playgroud)
应用程序.js
<Switch>
<Route path={`/login`} component={LoginMember} />
<Route path={`/registermember`} component={SignUp} />
<Authentication component={AuthenticateRoute} />
<Route component={Page404} />
</Switch>
const AuthenticateRoute = ({ match }) => (
<Switch>
<Authentication path={`${match.url}`} component={MainApp} />
<Route component={Page404} />
</Switch>
);
Run Code Online (Sandbox Code Playgroud)
主应用程序
<Switch>
<Route path={`/home`} component={Home} />
<Route path={`/profile/:id`} component={Profile} />
<Route component={Page404} />
</Switch>
Run Code Online (Sandbox Code Playgroud)
小智 7
构建应用程序并将其部署到服务器时,刷新页面有时会导致空白页面。我发现这个问题的解决方案在package.json文件中。
进行以下更改:
默认情况下,您的 package.json 可能包含如下内容:
"homepage": "./"或这个"homepage": "."
要解决该问题,只需将其更改为:
"homepage": "/"
Run Code Online (Sandbox Code Playgroud)
这将确保所有内容正确加载,包括存储、上下文、组件、redux 等。
我希望这可以帮助任何面临同样问题的人。以下是一些可能有用的其他详细信息:
该解决方案适用于 React Router v6。
该问题主要出现在嵌套路由中。我在非嵌套路由中测试了它,一切都按预期工作,因此嵌套路由似乎是这里的一个因素。
嵌套路由是指与原始路由位于不同文件内的路由。例如,在我的应用程序中,我有一个用于客户的首页和一个用于管理首页上显示的产品的仪表板。我的文件结构如下所示:
-src (Folder)
--App.js (Contains two main routes of /frontpages and /dashboard, which render the files from the routes folder)
--Routes (Folder)
---Dashboard.jsx (Contains nested dashboard routes)
---Frontpages.jsx (Contains nested frontpage routes)
--Components (Folder)
---All the files that get rendered in the routes folder components.
Run Code Online (Sandbox Code Playgroud)
从你的代码来看,
<Switch>
<Route path="/" component={App} />
<Route component={Page404} />
</Switch>
Run Code Online (Sandbox Code Playgroud)
<Route path="/" component={App} />它会导致为每个路由渲染App组件。因此,如果刷新页面,Page404将没有机会渲染它。
解决方案 :
放exact 为/.
<Route exact path="/" component={App} />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16253 次 |
| 最近记录: |