H
H
hbrmdc2015-06-25 17:28:26
Network administration
hbrmdc, 2015-06-25 17:28:26

How to force React Router to update content when navigating similar pages with the same Handler with dynamic path?

I have this Route:

<Route name="itemDetails" handler={ItemDetails} path="/item/:id"/>

it leads to the full description page of the product.
On such a page there are "similar offers" containing a Link leading to the same page with a full description of another product. Handler, naturally the same - ItemDetails.
I click on Link, the page address in the browser's address bar changes, but the content stays the same. To update the content, you have to refresh the page.
In cases of transition between pages with different handlers, the content is updated and everything works fine.
Why is that? How to force content to update?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2015-06-26
@iNikNik

What version of react, router?
Try using the componentWillReceiveProps method - it should be called when the route parameters (in your case, the ID) change.
When the component receives new properties (props) - it is redrawn. The problem can be if you, for example, use the parameters of your route through state:

class ControllerComponent extends Component {

    super() {
        super(props);
        this.state = { itemId: this.getParams().id };
    }

    //...

    render() {
        return (
            <div>
                <p>Blah blah blah</p>
                <SomeComponent itemId={this.state.itemId}/>
            </div>
        );
    }
}

At the same time: when the id changes, the ControllerComponent component is redrawn, but the state has not changed, so the old id will get into SomeComponent and it may seem that nothing has changed.
class ControllerComponent extends Component {

    super() {
        super(props);
        this.state = { itemId: this.getParams().id };
    }

    componentWillReceiveProps(nextProps) {
        this.setState({ itemId: this.getParams().id });
    }

    //...

    render() {
        return (
            <div>
                <p>Blah blah blah</p>
                <SomeComponent itemId={this.state.itemId}/>
            </div>
        );
    }
}

Then everything will be ok. By the way, according to the docs componentWillReceiveProps :
So we will not render our component once again. Success)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question