简体   繁体   English

React 渲染和按钮点击重定向

[英]React rendering and button click redirecting

I'm beginner in React, so it's my first application in React.我是 React 的初学者,所以这是我在 React 中的第一个应用程序。

Here this is my App.js file.这是我的App.js文件。

import './App.css';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import Login from './componants/Login';
import Home from './componants/Home';

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/login" component={Login}/>
        <Route exact path="/home" component={Home}/>
      </Switch>
    </Router>
    
  );
}

export default App;

And I'm exporting it in index.js file.我将它导出到 index.js 文件中。 This is my Login.jsx file.这是我的 Login.jsx 文件。

import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import './login.css';
import { useHistory } from 'react-router-dom';

function Login() {
    let history = useHistory();

    return (
        <section>
            <form>
                <h1>Note Maker</h1>
                <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter your email"></input>
                <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Enter your password"></input>
                <button onClick={() => { history.push("/home"); }} type="submit" class="btn">Login</button>
            </form>
        </section>
        
    );
}

export default Login;

Whenever I click on button it will take me to the /home route it is ok.每当我单击按钮时,它都会将我带到/home路线,这没关系。

Here I have a doubt whenever I start my App it will run on localhost:3000 , but my routes are /login and /home because of this I have to write localhost:3000/login for rendering login page I don't want this I want to render it on localhost:3000 and in that code also my button click redirecting should work properly.在这里,每当我启动我的应用程序时,我都会怀疑它会在localhost:3000上运行,但是我的路由是/login/home因为这个我必须编写localhost:3000/login来呈现登录页面我不想要这个我想要在localhost:3000上呈现它,并且在该代码中,我的按钮单击重定向也应该可以正常工作。

Else suggest me how to redirect to another route on button click.否则建议我如何在单击按钮时重定向到另一条路线。

I think that我觉得

<Route exact path="/" component={Login}/>

Should do the job应该做的工作

There are 2 solutions for this有2个解决方案

1> If you want to render localhost:3000 1> 如果要渲染localhost:3000

Add a Route for / in your App.js file在 App.js 文件中为 / 添加路由

<Route exact path="/" component={Login}/>

2>If you don't want to render localhost:3000 Redirect your page to login when the component is loaded. 2>如果你不想渲染localhost:3000在组件加载时重定向你的页面登录。 Adding something like this in your App.js will help在您的App.js中添加类似的内容会有所帮助

useEffect(()=>{
   history.push('/login')
},[])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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