Below is my code
class LoginContainer extends Component {
...
render() {
return <LoginApp isAuthenticated={this.props.isAuthenticated} />
}
}
/* ==> Implemetation of LoginApp is like below <== */
import { browserHistory } from 'react-router';
class LoginApp extends Component {
...
render() {
if (this.props.isAuthenticated) {
browserHistory.push('/dashboard');
return null;
}
/* code to render login form elements....*/
}
}
This code was giving warning like below when true is passed as value of isAuthenticated to LoginApp
Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.
As of now not able to make any changes in LoginApp component so made a small workaround in LoginContainer (which I really didn't like)
Changes I brought is
New implementation of LoginContainer is as below
class LoginContainer extends Component {
...
componentDidMount() {
if (this.props.isAuthenticated) {
browserHistory.push(prependAppRoute('/'))
}
}
componentDidUpdate() {
if (this.props.isAuthenticated) {
browserHistory.push(prependAppRoute('/'))
}
}
render() {
return <LoginApp />
}
}
And now I don't have that warning & I am in a mode - My code is working (As there is no warnings) but I don't know why 🙄??
React version: 15 React-router version: 2.8.1
If you call something in the render, not only do you have to actually wait for it render for your action to happen -- but you risk an infinite loop.
React runs by checking if props have changed, then re-renders. React Router changes the page through props. If you changed the state inside your render, the component would be caught in an infinite loop (rendering, updating the state, re-rendering, updating, etc etc).
It works when you make it a "side effect", using a pure function, or by changing the props during appropriate lifecycles (like componentDidMount() or willReceiveProps()). This allow's React to handle rendering, and re-rendering, of components properly when comparing props.
Diego Bernal made a great recommendation to abstract the code into a HOC, which is basically a pure function that accepts props and returns your child component (the page) when conditions are met.
What if you handled that at the Route level somehow? Via a higher-order component maybe?
If you made that abstraction, you could potentially apply the HOC to any other component that might need it.
Gijo Varghese
A WordPress speed enthusiast
If you want to redirect from the render, use
<Redirect>component