У меня есть форма входа в систему, которая при нажатии вызывает следующую функцию.
При суммировании получает ответ от API, если он действителен, устанавливает повара ie, а затем перенаправляет с помощью this.props.history.push()
handleSubmit(event) {
event.preventDefault();
const { email, password } = this.state;
axios({
method: 'post',
url: 'http://localhost:3003/login',
data: qs.stringify({ email, password }),
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
}
}).then(res => {
console.log("set cookie")
//the accestoken is set as a cookie in order to check routes
Cookies.set('accesstoken', res.data.accesstoken);
console.log("those are the props")
console.log(this.props);
this.props.history.push('/'); //the bug
}).catch(err => {
console.log(err)
})
}
Но проблема, с которой я столкнулся, заключается в том, что при первом входе в систему перенаправление не работает. Он устанавливает все файлы cookie и все такое, но фактически никогда не перенаправляет пользователя в нужный каталог. Поэтому я вынужден перенаправить себя, набрав желаемый маршрут в строке поиска браузера.
Это означает, что, как только я вхожу в нужный каталог, если я выхожу из системы (в основном удаляя файлы cookie), и пытаюсь войти снова. На этот раз перенаправление работает.
Это будет работать до тех пор, пока я не очистлю весь свой кэш с помощью ctrl + F5, что вызывает ту же проблему, с которой я столкнулся при первом входе в систему, поэтому мне пришлось снова перенаправить себя вручную.
РЕДАКТИРОВАТЬ: Вот так выглядят мои маршруты
<BrowserRouter>
<Switch>
<Route exact path="/login" render={(props) => <LoginPage {...props}/>} />
<PrivateRoute authed={this.state.isAuthenticated} exact path="/" render={(props) => <RegisterPage />} />
</Switch>
</BrowserRouter>
А это мои личные маршруты
import { Route } from 'react-router-dom';
import React from 'response'; import {Redirect} из'act-router ';
export default ({ component: Component, render: renderFn, authed, ...rest }) =>{
//The privateroute is fed with the auth state of app.js and evaluates the render based on that . If flase always renders "/"
if (Component){
return (
<Route
{...rest}
render={props =>
authed === true ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)
}
/>
)
} else {
return ( //Second case is for iframe based renders
<Route {...rest} render={props => authed === true ? renderFn(props) : <Redirect to={{ pathname: '/login', state: { from: props.location } }} /> } />
);
}
}
EDIT2:
app. js
constructor(props) {
super(props);
console.log("PROPS APPJS")
console.log(props)
//checks if user is autheticated within the system in order to manage routes
this.state = {
authenticationChecked: false,
isAuthenticated: false
}
}
componentDidMount() {
//calls the auth service to decide the auth state value
isAuthenticated().then((result) => {
if (result === true) {
this.setState({ isAuthenticated: true, authenticationChecked: true})
} else {
this.setState({ isAuthenticated: false, authenticationChecked: true})
}
});
}
login = (email, password) => {
var thiscomponent = this;
axios({
method: 'post',
url: 'http://localhost:3003/login',
data: qs.stringify({ email, password }),
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
}
}).then(res => {
console.log("set cookie")
//the accestoken is set as a cookie in order to check routes
Cookies.set('accesstoken', res.data.accesstoken);
console.log("those are the props")
console.log(this.props);
this.setState({ isAuthenticated: true }, () => {
thiscomponent.props.history.push('/'); //the bug
})
}).catch(err => {
console.log(err)
})
}
.
.
.
.
.
.
.
<BrowserRouter>
<Switch>
<PrivateRoute authed={this.state.isAuthenticated} exact path="/" render={(props) => <NewLandingPage login={this.login} {...props} exact />} />
</Switch>
</BrowserRouter>
Страница входа
handleSubmit(event) {
const { email, password } = this.state;
this.props.login(email, password)
event.preventDefault();
}
РЕДАКТИРОВАТЬ: реквизиты страницы входа
{"history":{"length":15,"action":"POP","location":{"pathname":"/login","search":"?email=test4%40test.com&password=test","hash":""}},"location":{"pathname":"/login","search":"?email=test4%40test.com&password=test","hash":""},"match":{"path":"/login","url":"/login","isExact":true,"params":{}}}