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.
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...