Here's another example. Say in javascript I want to navigate to a page 'login', here's a way to do it. window.location = 'login';
And there I go!In react, well it really depends on what version. If I'm doing pre-hook (pre 16.18 or so) classes, first I need to make sure my constructor brings in props that I call a super on. Huh? No no stay with me. Then I have a this.props.history object and I push a new entry on to the stack like so this.props.history.push('login'); Remember to make sure you use the fat-arrow to pass the this reference downward and that you export your class using withRouter. Effectively here's the replacement code: import React from 'react';
import {withRouter} from 'react-router';
Class A extends React.Component {
constructor(props) {
super(props);
}
fn() {
this.props.history.push('login');
}
}
export default withRouter(A);
And even then you may still have to "debug" this because it may "break" for inexplicable reasons. Because "In order to make use of history in the App component use it with withRouter. You need to make use of withRouter only when your component is not receiving the Router props,This may happen in cases when your component is a nested child of a component rendered by the Router or you haven't passed the Router props to it or when the component is not linked to the Router at all and is rendered as a separate component from the Routes." Again, we are replacing: window.location = 'login';
That is our only goal hereHow is this easier then the first one? It isn't. What problem has been solved? None. Does it take less time? No. Is this less typing? Less code? No. Less complexity? No. Are difficult things less difficult? No. Fragile things more robust? No. No none of this. It runs away from more reusable, self-contained, portable code as fast as possible. It gets in a rocket car and fires up the engines to go Mach 1 in the wrong direction. It's a giant tangled spaghetti dish of the worst anti-patterns in software engineering as a requirement for it to work. |