【问题标题】:How do I link routes in React with react-router-dom dynamically using button?如何使用按钮将 React 中的路由与 react-router-dom 动态链接?
【发布时间】:2020-05-23 00:31:42
【问题描述】:

我对使用 React 和 JSX 非常陌生,不确定如何在我的 react 应用程序中动态设置链接。我正在尝试使其在登录页面上,如果用户成功输入了他们的用户名和密码,它会重定向到主页,如果它们不匹配,它将重新加载登录页面。此登录表单对 Flask API 进行 fetch 调用,该 API 在用户名和密码与我的数据库正确匹配时返回成功。将登录页面链接到注册页面的按钮目前可以使用,但是使用类似的逻辑不适用于登录按钮

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter } from 'react-router-dom';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.css';
import 'semantic-ui-css/semantic.min.css'

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

App.js

import React, {useEffect, useState, Component} from 'react';
import './App.css';
import {NewUserInfo} from './components/NewUserInfo';
import {Login} from './components/Login';
import {Register} from './components/Register';
import {Container} from "semantic-ui-react";
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import Homepage from './components/Homepage';
import Tabs from './components/Tabs';
//import Header from './components/Header';
import Journal from './components/Journal';
import Survey from './components/Survey';
import Profile from './components/Profile';


function App(){
    return (
      <div>
        <Switch>
          <Route exact path="/" component={Login}/>
          <Route path="/register" component={Register}/>
          <Route path="/homepage" component={Homepage}/>
          <Route path="/profile" component={Profile}/>
        </Switch>
      </div>

    );
}

export default App;

Login.js

import React, { Component, useState } from "react";
import {Button, Form, FormGroup, Label, Input} from 'reactstrap';
export const Login = () => {
    const [email_or_username, setName] = useState('');
    const [password, setPassword] = useState('');
    const [is_contributor, setContributor] = useState(false);
    var ref = "/";
    return (           
        <div> 
            <Form className="login-form">
                <h1>
                <div className="text-right">
                    <Button
                        href="/register"
                        className=" btn-dark text-right">
                        sign up
                    </Button>
                </div>
                <span className="font-weight-bold">Mindify</span>
                </h1>
                <FormGroup>
                    <Label>Username or Email</Label>
                    <h2></h2>
                    <Input 
                        value={email_or_username} 
                        placeholder = "Username or Email" 
                        onChange={e => setName(e.target.value)}/>
                </FormGroup>

                <FormGroup>
                    <label>Password</label>
                    <h2></h2>
                    <Input 
                        value={password} 
                        placeholder = "Password"
                        onChange={e => setPassword(e.target.value)}/>
                </FormGroup>

                <FormGroup>
                    <div className="text-center">
                    <Input 
                        type="checkbox"
                        value={is_contributor}
                        onChange={e => setContributor(e.target.checked)}/>
                        Contributor
                    </div>                    
                </FormGroup>


                <Button onClick={async () =>{
                     const login = {email_or_username, password, is_contributor};
                     console.log(JSON.stringify(login));
                     const response = await fetch('http://127.0.0.1:5000/api/login', {
                         method: 'POST',
                         headers:{
                            'Content-Type': 'application/json'
                         },
                         body: JSON.stringify(login)
                     })
                     .then(response => {
                         console.log(response.status);
                         if (response.status === 201) {
                            console.log("Successful Login"); 
                            ref="/homepage";
                            console.log(ref);
                            //redirect to home page
                         }
                         else if (response.status === 204) {
                            console.log("Invalid Username or Password or Incorrect Permissions");
                            ref="/";
                            console.log(ref);
                            // reload login page
                         }
                     })
                     .catch(error => console.log(error))

                    }}
                    href={ref}
                    className="btn-lg btn-dark btn-block">
                    Log in</Button>

            </Form>
        </div>);


}

【问题讨论】:

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


    【解决方案1】:

    在这种情况下,您可以通过useHistory 使用history 来动态更改路由。

    你在组件中获取历史对象:const history = useHistory()

    然后您可以使用history.push(ref)history.replace(ref) 动态推送或替换当前路由

    import React, { Component, useState } from "react";
    import {Button, Form, FormGroup, Label, Input} from 'reactstrap';
    import {useHistory} from 'react-router-dom'
    export const Login = () => {
        const [email_or_username, setName] = useState('');
        const [password, setPassword] = useState('');
        const [is_contributor, setContributor] = useState(false);
        const history = useHistory()
        return (           
            <div> 
                <Form className="login-form">
                    <h1>
                    <div className="text-right">
                        <Button
                            href="/register"
                            className=" btn-dark text-right">
                            sign up
                        </Button>
                    </div>
                    <span className="font-weight-bold">Mindify</span>
                    </h1>
                    <FormGroup>
                        <Label>Username or Email</Label>
                        <h2></h2>
                        <Input 
                            value={email_or_username} 
                            placeholder = "Username or Email" 
                            onChange={e => setName(e.target.value)}/>
                    </FormGroup>
    
                    <FormGroup>
                        <label>Password</label>
                        <h2></h2>
                        <Input 
                            value={password} 
                            placeholder = "Password"
                            onChange={e => setPassword(e.target.value)}/>
                    </FormGroup>
    
                    <FormGroup>
                        <div className="text-center">
                        <Input 
                            type="checkbox"
                            value={is_contributor}
                            onChange={e => setContributor(e.target.checked)}/>
                            Contributor
                        </div>                    
                    </FormGroup>
    
    
                    <Button onClick={async () =>{
                         const login = {email_or_username, password, is_contributor};
                         console.log(JSON.stringify(login));
                         const response = await fetch('http://127.0.0.1:5000/api/login', {
                             method: 'POST',
                             headers:{
                                'Content-Type': 'application/json'
                             },
                             body: JSON.stringify(login)
                         })
                         .then(response => {
                             console.log(response.status);
                             if (response.status === 201) {
                                console.log("Successful Login"); 
                                const ref="/homepage";
                                console.log(ref);
                                //redirect to home page
                                history.push(ref)
                             }
                             else if (response.status === 204) {
                                console.log("Invalid Username or Password or Incorrect Permissions");
                                const ref="/";
                                console.log(ref);
                                // reload login page
                                history.push(ref)
                             }
                         })
                         .catch(error => console.log(error))
    
                        }}
                        className="btn-lg btn-dark btn-block">
                        Log in</Button>
    
                </Form>
            </div>);
    
    
    }
    

    【讨论】:

      【解决方案2】:

      在 react-router-dom v6 中,您将使用 useNavigate() https://reactnavigation.org/docs/use-navigation/

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      【解决方案3】:

      您可以使用“导航”作为返回(它仅在组件安装的开始对我有用(无函数调用)):

      import { Navigate } from 'react-router-dom';
      
      function X() {
      
         if (roles && currentUser && roles.indexOf(currentUser.role) === -1) {
             return (<Navigate to='/notfound'></Navigate>);
         }
         ...
      } export { X };
      

      或者您可以使用“useNavigate”。对于“useNavigate”,您必须先创建一个 const,然后在函数调用中使用 return -> return navigate("/..."):

      import { useNavigate } from 'react-router-dom';
      function LoginPage() {
          const navigate = useNavigate();
      
          const handleLogin = () => {
             if (!(user.username && user.password)) {
                 return;
             }
             UserService.login(user)
                 .then(data => {
                     console.log("login successful")
                     return navigate("/");
                  }, error => {
                     setErrorMessage("Username or password is wrong.");
                     console.log("log in failed.")
                  });
          }
      
      ...
      } export { LoginPage };
      

      所以当组件被挂载(没有函数调用)时导航,函数调用时使用导航。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-30
        • 2021-06-30
        • 2020-11-05
        • 2022-07-07
        • 2018-06-04
        • 1970-01-01
        • 2022-01-09
        相关资源
        最近更新 更多