-
-
Notifications
You must be signed in to change notification settings - Fork 10.6k
Calling a function in a component when a query parameter changes #579
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I was wondering the same. Any hints? :-) Cheers, |
Edit: You should use #579 (comment), not this.
/*
Usage:
this.setQuery("search","42");
this.onQueryChange("search", console.log.bind(console));
*/
var Navigation = _.extend({
setQuery: function (dict) {
var q = this.context.getCurrentQuery();
for(var i in dict){
if(dict.hasOwnProperty(i)){
q[i] = dict[i] || undefined; //falsey values shall be removed.
}
}
this.replaceWith(this.context.getCurrentPath(), this.context.getCurrentParams(), q);
},
}, ReactRouter.Navigation);
_.extend(Navigation.contextTypes, ReactRouter.State.contextTypes);
var State = _.extend({
getInitialState: function () {
this._query = this.context.getCurrentQuery();
this._queryWatches = [];
},
onQueryChange: function (key, callback) {
this._queryWatches.push({
key: key,
callback: callback
});
},
componentWillReceiveProps: function (nextProps, nextState) {
var q = this.context.getCurrentQuery();
for (var i = 0; i < this._queryWatches.length; i++) {
var watch = this._queryWatches[i];
if (this._query[watch.key] !== q[watch.key]) {
watch.callback(this._query[watch.key], q[watch.key], watch.key);
}
}
this._query = q;
}
}, ReactRouter.State); |
If I need that info I pass the params/query down my route view hierarchy and let react's lifecycle hooks help me out. Router.run(routes, (Handler, state) => {
React.render(<Handler {...state}/>, document.body);
});
// and then everywhere else:
<RouteHandler {...this.props}/> Now its available here on every component: componentWillReceiveProps (nextProps) {
var oldQuery = this.props.query;
var newQuery = nextProps.query;
} edit thanks @abergs |
@ryanflorence I believe you meant:
|
FWIW, in 0.13.2 |
Right now I'm working on moving some of our component state into query parameters so that pages are bookmarkable and other components can cleanly change the values.
It looks like react-router will call
.render
when a query parameter changes, but it's not clear how to tell which part of the URL / which query parameter changed, and the work I'm doing is outside of .render, in an onChange or componentDidUpdate lifecycle method.Is there a clean way of implementing this? It seems like I either need to:
The text was updated successfully, but these errors were encountered: