React-router 重定向仅在重新加载时显示页面 [英] React-router Redirection displays page only when reloading it

查看:55
本文介绍了React-router 重定向仅在重新加载时显示页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 React 应用程序中使用 react-router,但在启动应用程序时遇到了问题.首先,我得到一个没有任何错误的空白页面,当我重新加载页面时,我得到了内容.

I'm using react-router in a react app and I faced an issue while launching the app. First, I got a blank page without any error, when i reload the page I got the content.

index.tsx:

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import Root from './app/Root';
import * as serviceWorker from './serviceWorker';
import store from './app/store';

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <Root />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root'),
);

Root.tsx:

import React from 'react';
import {Route, Router, Switch} from 'react-router-dom';
import App from './App';
import SignIn from 'features/authentication/signIn/SignInContainer';
import SignUp from 'features/authentication/signUp/SignUpContainer';
import history from 'browserHistory/index';
const Root = (): JSX.Element => (
  <Router history={history}>
    <Switch>
    <Route exact path="/" component={App} />
    <Route exact path="/signin" component={SignIn} />
    <Route path="/signup" component={SignUp} />
   </Switch>
  </Router>
);

export default Root;

当我尝试使用 BrowserRouter 而不是 Router 时,我没有问题,但是如果我使用 history.push() 在 tsx 文件之外.这就是为什么我需要使用 Router 代替.有一个类似的问题 反应路由器重定向页面但组件没有被渲染,但我认为我的路由器包装了主要的应用程序组件.我在代码中错误配置了什么?

When I tried the BrowserRouter instead of Router I hadn't the issue but BrowserRouter does not work if I use history.push() outside a tsx files. That's why I need to use Router instead. There is a similar question React router redirects the page but component doesn't get rendered but I think that my Router wrap the main app components. What did I misconfigured in the code?

推荐答案

您的代码似乎是正确的,因为 Router 在提供 历史对象.

You code seems correct as Router works after providing it a history object.

因此,请确保您已正确创建history:

So, make sure you have properly created history:

import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
export default history;

并且,还要确保您使用的是 history 的nofollow noreferrer">第 4 版,而不是 版本 5(未解决的问题).

And, also ensure that you are using version 4 of history, not version 5 (open issue).

这篇关于React-router 重定向仅在重新加载时显示页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆