Skip to content

Instantly share code, notes, and snippets.

@MathieuLorber
Last active November 22, 2017 06:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MathieuLorber/61ee584e375c41cd60038a11a9bf437b to your computer and use it in GitHub Desktop.
Save MathieuLorber/61ee584e375c41cd60038a11a9bf437b to your computer and use it in GitHub Desktop.
Attempt of react-router v4 onEnter replacement
import React, {PropTypes} from "react";
import {BrowserRouter as Router, Route, Link} from "react-router-dom";
// from the documentation Auth example
// https://reacttraining.com/react-router/examples
const Test = () => (
<Router>
<div>
<ul>
<li><Link to="/test/1">1</Link></li>
<li><Link to="/test/2">2</Link></li>
<li><Link to="/test/3">3</Link></li>
</ul>
<MyRoute path="/test/:id"
render={(state) => {
// seems ok ?
console.log('MyRoute render');
return <MyComponent match={state.match}/>;
}}/>
</div>
</Router>
);
class MyRoute extends Route {
componentDidMount() {
// called once
console.log('MyRoute componentDidMount');
console.log(this.props);
}
// everything is ko !
// componentWillMount() {
// console.log('MyRoute componentWillMount');
// console.log(this.props);
// }
componentWillReceiveProps() {
// never called
console.log('MyRoute componentWillReceiveProps');
console.log(this.props);
}
}
class MyComponent extends React.Component {
componentWillMount() {
// called once
console.log('MyComponent will mount');
console.log(this.props);
}
componentDidMount() {
// called once
console.log('MyComponent did mount');
console.log(this.props);
}
componentWillReceiveProps() {
// needs manuel check
console.log('MyComponent componentWillReceiveProps');
console.log(this.props);
}
render() {
return <p>
{this.props.match.params.id}
</p>
}
}
export default Test
@usefksa
Copy link

usefksa commented Nov 22, 2017

I used the following code

class MyComponent extends React.Component {
	componentWillReceiveProps() {
		//do what you want to do in onEnter here
		// example dispatch action to redux
		// I use the following here
		if (this.props.match.url !== nextProps.match.url) {
			fetch(nextProps.match.url);
		}
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment