Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

reactjs - 如何使用history.push()函数重定向页面(How to redirect the page with history.push() function)

I have worked on a sign in page and this is a page for controlling unauthorized access.

(我已经在登录页面上工作,这是一个用于控制未经授权的访问的页面。)

But, Page redirection is not working here,

(但是,页面重定向在这里不起作用,)

Here is my code   

import React from 'react';
import { Layout, Menu, Breadcrumb, Button } from 'antd';
import { BrowserRouter, Link, Redirect } from 'react-router-dom';

const { Header, Content, Footer } = Layout;
class MainPage extends React.Component {
  constructor(props) {
  super(props);     
  }  
state= {
      redirect: false,
  }

 render()
{
 let users=localStorage.getItem('user');
 function logOut() {
 if (true) {
 localStorage.clear();
 this.props.history.push('/Signin');
    }
    }
function AuthPage () {
return(
     <div>      
   { 
       (users) ? (<Layout>

   <Content>
              <div className="main-content">
                    <Link to="/Profile">Profile {users}</Link> | 
                    <Link to="/Topics">Topics</Link> | 
                   <Button onClick={logOut} type="link" >Logout</Button>
              </div> 
          </Content>
        </Layout> 
        ) : (<div>Need to login</div>
            )
   }
   </div>
 );
 }
   return(AuthPage());
  }
 }

 export default MainPage;

I also tried this:

(我也试过这个:)

This is Also Not working in redirection.

(这在重定向中也不起作用。)

 import React from 'react'
 import  { Redirect } from 'react-router-dom'

  const ProtectedComponent = () => {
     if (authFails)
     return <Redirect to='/Signin'  />
     }
     return <div> My Protected Component </div>
   }

What is the proper way of implementing Redirect in React.js.

(在React.js中实现重定向的正确方法是什么?)

  ask by Dhamotharan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use both Redirect and history for the redirection in React.js.

(您可以在React.js中使用重定向历史记录进行重定向。)

But there is slightly difference in the way both are implemented.

(但是两者的实现方式略有不同。)

Redirect is very explicit and history is implicit and less number of lines.

(重定向非常明确,历史记录是隐式的,行数更少。)

Please have a look at this link ( programmatically redirect in react.js ) to know more on redirect in react.js with example.

(请看一下这个链接( 在react.js中编程方式重定向 ),以了解更多有关react.js中重定向的示例。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...