I am doing a login page, I want that when the person is correctly logged in to redirect him to a page but without reloading, and I tried to do it with the useHistory but it does not work for me
import React, { Component } from 'react'
import './main.css';
import {BrowserRouter as Router, Switch, Route, Link, Redirect,
useHistory,
useLocation, browserHistory, withRouter} from 'react-router-dom';
import Register from './components/ComponentRegister'
import Login from './components/ContainerLogin'
import ChatPrincipal from './Chat/ChatPrincipal'
event code
login = (username, password) =>{
const history = useHistory()
fetch('/api/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({username: username, password: password})
})
.then(r => r.json())
.then(data =>{
console.log(data.status)
if(data.status === 200){
console.log('si')
this.setState({
status: data.status,
message: data.message,
username: username
})
this.userSearch()
// window.location.href = "/"
history.push('/') <===================================
}else{
this.setState({
messageError: data.message,
status: data.status
})
console.log('Error')
const error = document.getElementById('Error')
}
})
}
I don't know why it doesn't work for me, but if anyone knows a way to fix it or a library to redirect without updating please help me
You can try
history.replace({ pathname: '/'})
Here is working demo
Please note, that in this case you need to handle changing content after replacing url
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.