I am creating an app in Reactjs. I have app.js, dashboard.js and login.js.
in my app.js i have a link to login page. i wanted to redict to dashboard page from login page. In my login, I am making a call to backend service and validating user credentails. I have the following code in login.js
request.post(
options,
function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log('redirecting');
// browserHistory.push('/dashboard')
// ( <Redirect to={{
// pathname: '/dashboard'
// }}/>)
// this.props.history.push('/dashboard');
<Redirect to='./dashboard' /> // redirection is not working here
}else{
console.log(error);
}
}
);
When i enter user credentials, After the validation i could see redirecting message in console however the page is not redirecting.
I am using react-router-dom
. Can you please help me to identify what went wrong ?
You are trying to put jsx code inside a function. jsx code work inside render function and on the click of <Redirect to='./dashboard' />
will redirect to dashboard page. But you are trying to redirect programmatically.
Use browserHistory.push('/dashboard')
for redirect from a function.
This is a reference Navigating Outside of Components
I believe you may only use <Redirect>
as a rendered element from within one of your components (not from within a JS function).
Therefore, from your login
page where you are calling this function how about setting a variable after the response from the server to indicate whether the user was successfully logged in and then, based on its value, display the <Redirect>
.
For example,
request.post(
options,
function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log('redirecting');
this.setState({
isLoggedIn: true
})
}else{
console.log(error);
}
}
);
and in your render
method:
if (this.state.isLoggedIn) {
return <Redirect to='./dashboard' />
}
return (
// If the user is not logged in, return the usual login page...
)
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.