gpt4 book ai didi

How do I link routes in React with react-router-dom dynamically using button?(如何使用button动态链接React中的路由与react-router-dom?)

转载 作者:bug小助手 更新时间:2023-10-25 19:31:54 33 4
gpt4 key购买 nike



I am very new to using React and JSX and was unsure how to dynamically set a link in my react app. I am trying to make it so that on the login page, if the user successfully inputs their username and password, it redirects to the homepage, and if they do not match it would reload the login page. This login form makes a fetch call to a Flask API, which returns success on a correct matching of the username and password with my database. The button that links the login page to the signup page currently works, but using similar logic does not work with the login button

我对使用Reaction和JSX非常陌生,不确定如何在我的React应用程序中动态设置链接。我正在努力使它在登录页面上,如果用户成功地输入他们的用户名和密码,它重定向到主页,如果他们不匹配,它将重新加载登录页面。该登录表单对FlaskAPI进行了一次FETCH调用,如果用户名和密码与我的数据库匹配正确,则返回成功。将登录页面链接到注册页面的按钮当前有效,但使用类似逻辑的按钮不适用于登录按钮



index.js

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

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

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>);


}

更多回答
优秀答案推荐

In this case, you can use history via useHistory to dynamically change the route.

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



You get the history object in the component with: const history = useHistory()

您可以使用以下命令获取组件中的历史记录对象:const History=useHistory()



Then you can dynamically push or replace the current route using: history.push(ref) or history.replace(ref)

然后,您可以使用以下命令动态推送或替换当前路径:history.ush(Ref)或history.place(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>);


}


In v6 of react-router-dom you would use useNavigate()
https://reactnavigation.org/docs/use-navigation/

在REACT-RUTER-DOM的V6中,您将使用Navigate()https://reactnavigation.org/docs/use-navigation/



You can either use "Navigate" as a return (It worked for me only in the beginning when a component mounts (no function call)):

您可以使用“导航”作为回车(我只在一开始挂载组件时使用它(没有函数调用)):


import { Navigate } from 'react-router-dom';

function X() {

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

Or you can use "useNavigate". For "useNavigate" you have to create a const first and in a function call you do it with return too -> return navigate("/..."):

或者,您可以使用“useNavigate”。对于“useNavigate”,您必须首先创建一个常量,并在函数调用中使用Return Too->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 };

So Navigate for while component is getting mounted (no function call) and useNavigate for when function calls.

因此,在挂载组件时导航(无函数调用),在函数调用时使用导航。



try this :

试试这个:


 <BrowserRouter>
<React.StrictMode>
<App />

</React.StrictMode>



更多回答

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

您的答案可以通过其他支持信息来改进。请编辑以添加更多详细信息,如引用或文档,以便其他人可以确认您的答案是正确的。你可以在帮助中心找到更多关于如何写出好答案的信息。

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com