K
K
Ken Jee2018-08-13 18:00:32
React
Ken Jee, 2018-08-13 18:00:32

Why does ReactJS not render the component on history.push?

Why is the Login component not rendering after a new /user/login URL has been pushed with history.push? But with an explicit request for the /user/login URL, the Login component is rendered as needed.

import './../bootstrap'

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Route, Switch } from 'react-router-dom'
import {withRouter} from "react-router-dom"

import Header from './Header'

import Login from './Login'

import Footer from './Footer'

class App extends Component {

    componentWillMount() {

        if ( ! this.props.auth ) {

            this.props.history.push( '/user/login' )

        }

    }

    render() {

        return (

            <div>
                <Header />
                <Switch>
                    <Route path='/user/login' component={Login}/>
                </Switch>
                <Footer />
            </div>

        )

    }

}

const mapStateToProps = state => {

    return {

        auth: state.auth

    }

}

export default connect( mapStateToProps )( withRouter( App ) )

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Ken Jee, 2018-08-13
@Machez

Everything worked after I changed the export App
Variant which was and did NOT work:
Option that made everything work as it should:
Apparently the point is that withRouter is a higher-order function and in this case it should be applied to the result of the connect function .

P
Pavlo Ponomarenko, 2018-08-13
@TheShock

I understand that your state is not updated, in fact. Try to make a special wrapper that will not only change history, but also an additional state in the root element. Something like this:
this.setState({ currentUrl: '/user/login' })

M
Maxim, 2018-08-13
@maxfarseer

As already mentioned, React does not know anything about changing the history with history.push. But you can train it to react to this (just like react-router does, in fact) - see the section in Train Route to Respond to URL Changes

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question