简体   繁体   中英

React : How to redirect in react?

When login button is clicked, console log output 'Redirecting..' is seen. But, the Welcome component is not seen. No errors are also logged.

import React, { useState } from 'react';
import  { Redirect } from 'react-router-dom'
import './App.css';
import { Form, Input, Button, Checkbox } from 'antd';

function App() {
  const bgstyle={
      background:"linear-gradient(to right, #11998e, #38ef7d)",
      height:"100vh",display: 'flex',  justifyContent:'center', alignItems:'center',flexDirection: 'column'
  }
  let isLoggedIn = useState(false)
  const onFinish= function onfinish(data){
    isLoggedIn = data.password=="password"?true:false
    if(isLoggedIn){
      console.log('Redirecting..')
      return <Redirect to='/Welcome/' />
    }
  }

  return (
    <div style={bgstyle}>
      <h1 style={{color:'white'}}>Welcome</h1>
      <Form onFinish={onFinish}>
        <Form.Item name="username" rules={[{ required: true, message: 'Please enter your username!' }]}>
          <Input placeholder="Username"/>       
        </Form.Item>

        <Form.Item name="password" rules={[{ required: true, message: 'Please enter your password!' }]}>
          <Input.Password placeholder="Password"/>       
        </Form.Item>

        <Button type="primary" style={{width:200,borderColor:'gray',background:'gray'}} htmlType="submit">Login</Button>
      </Form>
    </div>
  );
  }
export default App;

Welcome.js code:

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
    <p>Welcome</p>,
  document.getElementById('root')
);

Should I use Route? What am I missing? I am just beginning in react. Please post any links that may help me understand more.

You should use history api from react-router-dom . You could access it with useHistory hook.

You could check this docs here

import React, { useState } from 'react';
import  { Redirect, useHistory } from 'react-router-dom'
import './App.css';
import { Form, Input, Button, Checkbox } from 'antd';

function App() {
  const bgstyle={
      background:"linear-gradient(to right, #11998e, #38ef7d)",
      height:"100vh",display: 'flex',  justifyContent:'center', alignItems:'center',flexDirection: 'column'
  }
 const history = useHistory();
  let isLoggedIn = useState(false)
  const onFinish= function onfinish(data){
    isLoggedIn = data.password=="password"?true:false
    if(isLoggedIn){
      console.log('Redirecting..')
      return history.push('/Welcome')    
  }

  return (
    <div style={bgstyle}>
      <h1 style={{color:'white'}}>Welcome</h1>
      <Form onFinish={onFinish}>
        <Form.Item name="username" rules={[{ required: true, message: 'Please enter your username!' }]}>
          <Input placeholder="Username"/>       
        </Form.Item>

        <Form.Item name="password" rules={[{ required: true, message: 'Please enter your password!' }]}>
          <Input.Password placeholder="Password"/>       
        </Form.Item>

        <Button type="primary" style={{width:200,borderColor:'gray',background:'gray'}} htmlType="submit">Login</Button>
      </Form>
    </div>
  );
  }
export default App;

What's happening in your code is basically that function is returning a react object but it's not rendering it, that's why you see console but no redirection happens. If you want this to work use if(isLooged) return outside the "onFinish" function. So it can Render on Dom and redirect successfully.

Also, You Have to define Routes as mentioned below if you want Redirect to work. Check the below code and set routes and login flow in the same way.

const [isLoggedIn, setLogin] = useState(false);

const onFinish = function onfinish(data){
    if(data.password === "password") setLogin(true);
}

if(isLoggedIn){
  console.log('Redirecting..')
  return <Redirect to='/Welcome' />
}
return (
<div style={bgstyle}>
  <h1 style={{color:'white'}}>Welcome</h1>
  <Form onFinish={onFinish}>
    <Form.Item name="username" rules={[{ required: true, message: 'Please enter your username!' }]}>
      <Input placeholder="Username"/>       
    </Form.Item>

    <Form.Item name="password" rules={[{ required: true, message: 'Please enter your password!' }]}>
      <Input.Password placeholder="Password"/>       
    </Form.Item>

    <Button type="primary" style={{width:200,borderColor:'gray',background:'gray'}} htmlType="submit">Login</Button>
  </Form>
</div>
)
}
export default App;

You Have to define Routes as mentioned below if you want Redirect to work

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import Root from './root'

ReactDOM.render(
  <Root />,
  document.getElementById('root')
);

Root.js:

import React from 'react'
import {Route, BrowserRouter, Switch} from 'react-router-dom'
import LoginComponent from './component/LoginComponent'; 
import WelcomeComponent from './component/WelcomeComponent';
import NotFoundPage from './NotFoundPage'

export default = () => {
    return (
      <BrowserRouter>
       <Switch>
        <Route exact={true} path={'/Welcome'} component={WelcomeComponent}/>
        <Route exact={true} path={'/Login'} component={LoginComponent}/>
        <Route component={NotFoundPage} />
       <Switch>
      <BrowserRouter/>
    )
}

After this your Redirect should work you can also use { usehistory } as mentioned in the first answer

Also, check this Programmatically navigate using react router using different versions but first, you have to implement Routes as mentioned above.

You can more information on https://reactrouter.com/web/guides/quick-start

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM