Search code examples
reactjsreact-routerurl-routing

A component in <Route> is not updating


Lately, I've been working on a React app that fetches data and pages from an API. Because of this, instead of creating, say, <Index />, <ContactUs />, <AboutUs /> etc. components, I've just placed a <Page /> component in the middle of the page. This is the component class, a bit simplified 𝐼 π“Œπ’Άπ“ˆ π’Ώπ“Šπ“ˆπ“‰ π“‰π‘œπ‘œ π“π’Άπ“π“Ž π“‰π‘œ "π“ˆπ’Ύπ“‚π“…π“π’Ύπ’»π“Ž 𝒾𝓉 𝒢 𝒷𝒾𝓉".

class Page extends Component {
    state = {
        content: ''
    }

    componentDidMount () {
        console.log(this.props)
        const component = this;
        fetch(`http://localhost:3001/pages/${this.props.location.pathname}`)
            .then((data) => {
                return data.json();
            }).then((response) => {
                component.setState({ content: response.content });
            })
            .catch((err) => {
                console.error(`An error was thrown! Error message: ${err}`);
            });
    }

    render () {
        return (
            <JsxParser
                components={ {
                    Button,
                    Typography
                } }

                jsx={ this.state.content }
            />
        )
    }
}

Page.propTypes = {
    location: PropTypes.object.isRequired
}

export default Router.withRouter(Page);

However, if I add <Router.Route component={ Page } /> and then, either through a <Link> or this.props.history.push()/replace(), change the current location, the components does not update and always displays the page corresponding to the original URL (the one just after reloading the page, before navigating to other URLs*). I really don't understand why it's not updating, although I also think that I'm probably just making an extraordinarily simple mistake...
ᡃˑ˒ᡒ αΆ¦ Λ’α΅—α΅ƒΚ³α΅—α΅‰α΅ˆ ᡘ˒ᢦⁿᡍ Κ³α΅‰α΅ƒαΆœα΅— ˑᡉ˒˒ ᡗʰᡃⁿ ᡃ ᡐᡒⁿᡗʰ ᡃᡍᡒ Λ’α΅’ ᡖˑᡉᡃ˒ᡉ α΅ˆα΅’βΏ'α΅— ᡇˑᡃᡐᡉ ᡐᡉ

EDIT:
I have tried to add a DidComponentUpdate method to the Page component; however, although the component does get a change in props every time the URL changes, all of the props regarding location (eg. this.props.location.pathname) stay the same.






* note that this is not necessarily the root URL, if the page loaded, for example, on /contacts, <Page /> will always stay there.


Solution

  • Although I didn't manage to directly update the component, I still managed to fire again componentDidMount() by wrapping it into an inline functional component, whicih was the was one that I actually rendered. I used this code

    <Router.Route path='/*' component={ function ({ match }) {
        return <Page path={ match.url } />
    } } />
    

    Apparently, it was simpler than I thought...