后退按钮在React中显示空白页面

时间:2020-07-16 19:59:00

标签: reactjs react-router react-router-dom

我正在尝试使用浏览器中的“后退”按钮,以便用户可以在我的react应用程序中顺利返回。有时它适用于特定的组件。例如,当我从主管转到Anfitrion时,它起作用,但是当我从Anfitrion转到Suprvisores时,或者在任何动态路线中,它都不起作用。 这是我路由器中的物品。

    <Router>

    <Switch>

            <Route exact path="/Anfitrion" component={PropiedadesRegistradas}/>
            <Route path='/AgregarPropiedad' component={AgregarPropiedad} />
            <Route path= "/AreasRegistradas/:propertyId" component={AreasRegistradas}/>
            <Route path= "/ItemsAreasRegistradas/:propertyId" component={ItemsAreasRegistradas}/>            
            <Route path="/ElementosDeArea/:areaId" component = {ElementosDeArea} />
            <Route path="/AgregarItems/:areaId/:propertyId" component = {AgregarItems} />
            <Route path="/AgregarArea/:propertyId" component = {AgregarArea} />

            <Route path="/supervisores" component={Supervisores}/>
            <Route path="/historial" component={Historial}/>
            <Route path="/desinfeccion" component={Desinfeccion}/>
            <Route path="/folios" component={Folios}/>    

            <Route path="/areasRegistradas" component={AreasRegistradas}/>
            <Route path= "/agregarSupervisor" component={AgregarSupervisor}/>
            <Route path="/detalle/:servicio/:hostId" component={Detalle} />
            <Route render={()=> <h3>Not found</h3>}/>

          </Switch>
    </Router>


这是我尝试使用useHistory Hook的方法,但是当我单击按钮时,它显示黑页:

import React from 'react'
import Button from '@material-ui/core/Button';
import { useHistory } from 'react-router-dom'



export default function AgregarItems({match}, props){
    let history = useHistory()
    return(
        <div>
        <Button onClick={() => history.goBack()}>Atrás</Button>
        </div>
    )
}

当我使用浏览器的后退和前进按钮时,它还会显示空白页。我正在阅读有关React Router的历史记录,但是我还没有发现任何有用的东西,而当我这样做时,它对React Router v3来说是有用的。

感谢您的帮助!

我正在使用:

  • “ react-dom”:“ ^ 16.13.1”,
  • “反应路由器”:“ ^ 5.2.0”,
  • “ react-router-dom”:“ ^ 5.2.0”,

2 个答案:

答案 0 :(得分:0)

只需对CRA进行测试。看看试试看。 您可能不需要使用withRouter

文件: ./PageOne.js

import React from 'react';
import { Link } from 'react-router-dom'

const PageOne = props => <div><h1>Click below</h1><Link to="/page2">Page 2</Link></div>;

export default PageOne;

文件: ./PageTwo.js

import React from 'react';

const PageTwo = props => <div><h1>Click Below</h1><button onClick={() => props.history.goBack()}>Go Back</button></div>;

export default PageTwo;

文件: ./index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import PageOne from './PageOne';
import PageTwo from './PageTwo';

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={PageOne} />
        <Route exact path="/page2" component={PageTwo} />
      </Switch>
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

==========更新=========

用于角色中间的路由中间件作为抽象的<PrivateRoute>

点击下面的运行代码片段,以查看其如何获得许可。

// IMPORTS
const { useState } = React;
// StackOverflow only allows HashRouter
// But replace with BrowserRouter
const { HashRouter, Switch, Route, Link, Redirect } = ReactRouterDOM;

/**
 *
 */
const NotPermitted = props => <div><h1>Not Permitted</h1><p>You need to be</p> <code>admin@admin.com</code><p>&nbsp;</p><Link to="/">Go Back Home</Link></div>;

/**
 *
 */
const AdminOnly = props => <div><h1>Admin Only</h1><p>You should only see this is your email is "admin@admin.com"</p></div>;

/**
 *
 */
const Dashboard = props => <div><h1>Dashboard</h1><p>Links</p><ul><li><Link to="/private">Private Page</Link></li><li><Link to="/adminonly">Admin Only</Link></li></ul></div>;

/**
 *
 */
const Login = props => {
  const onSubmit = event => {
    event.preventDefault();
    if (props.login) {
      props.login({
        email: event.target.email.value,
        password: event.target.password.value
      });
    }
  }

  return <div>
    <h1>Login</h1>
    <form onSubmit={onSubmit}>
      <p><input type="text" name="email" placeholder="Email" /></p>
      <p><input type="password" name="password" placeholder="Password" /></p>
      <p><button type="submit">Submit</button></p>
    </form>
    </div>
}

/**
 *
 */
const PrivatePage = props => <div><h1>Private Page</h1><p>Anyone logged in can see this page.</p><Link to="/">Go Back Home</Link></div>;

/**
 *
 */
const PrivateRoute = props => {
  const { component: Component, permitted, user, ...rest } = props;
  return (
    <Route
      {...rest}
      render={(routeProps) => 
        user
          ? permitted
            ? <Component {...routeProps} />
            : <Redirect to="/notpermitted" />
          : <Redirect to="/login" />
      }
    />
  );
}

/**
 *
 */
const App = props => {
  const [user, setUser] = useState(null);
  
  const login = ({ email, password }) => {
    setUser({
      email,
    });
  }
  
  const logout = () => {
    setUser(null);
  }
  
  return <div>
      {user && <button onClick={logout}>Logout</button>}
      <Switch>
        <Route exact path="/" render={() => user ? <Redirect to="/dashboard" /> : <Redirect to="/login" />} />
        <Route exact path="/login" render={(routeProps) => !user ? <Login login={login} {...routeProps} /> : <Redirect to="/dashboard" />} />
        <PrivateRoute user={user} permitted={true} exact path="/dashboard" component={Dashboard} />
        <PrivateRoute user={user} permitted={user && user.email === 'admin@admin.com'} exact path="/adminonly" component={AdminOnly} />
        <PrivateRoute user={user} permitted={true} exact path="/private" component={PrivatePage} />
        <PrivateRoute user={user} permitted={true} exact path="/notpermitted" component={NotPermitted} />
      </Switch>
      <hr />
      {user && <p><small>Debug JSON</small></p>}
      {user && <pre><code>{JSON.stringify(user, null, ' ')}</code></pre>}
      <p><small>Redirect Tests</small></p>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/login">Login</Link></li>
        <li><Link to="/dashboard">Dashboard</Link></li>
        <li><Link to="/adminonly">Admin Only</Link></li>
        <li><Link to="/private">Private</Link></li> 
        <li><Link to="/notpermitted">Not Permitted</Link></li> 
      </ul>
  </div>
}

/**
 *
 */
const Index = props => {
  return <div>
    <HashRouter>
      <App />
    </HashRouter>
  </div>
}

ReactDOM.render(<Index />, document.querySelector('#root'));
body {
font-family: Arial, sans-serif;
padding: 20px;
margin: 0;
}

form {
display: block;
}

input {
  height: 40px;
  padding: 0 12px;
  border-radius: 4px;
  border: 1px solid #efefef;
  min-width: 200px;
}

button {
  display: block;
  height: 40px;
  padding: 0 20px;
  background: blue;
  color: white;
  border-radius: 4px;
  border: none;
}

pre {
display: block;
margin-top: 20px;
}

code {
display: block;
  background: #efefef;
  padding: 20px;
}

h1 {
  font-size: 21px;
  padding-bottom: 20px;
  border-bottom: 1px solid #efefef;
  margin-bottom: 20px;
}

hr {
border: none;
height: 1px;
background: #efefef;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/react-router/umd/react-router.min.js"></script>
<script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>

<div id="root"></div>

答案 1 :(得分:0)

我通过从Rails应用程序中删除涡轮链接来解决此问题。信用:page is not rendering when I click back button with react-router