0

I just started, so I don't know if this is desired behavior or if I have missed something. I'm using the Flux architecture (specifically Reflux but that should not be relevant). In my super-simple test app:

var App = React.createClass({
    render: function () {
        return (
            <div className="container">
                <Header />
                <RouteHandler />
            <div>
        );
    }
});

var routes = (
    <Route name="app" path="/" handler={App}>
        <Route name="employees" handler={Employees}/>
        <Route name="company" handler={Company}/>
        <Route name="timesheets" handler={Timesheets}/>
        <DefaultRoute handler={Company} />
    </Route> 
);

Router.run(routes, function (Handler) {
    React.render(<Handler/>, document.getElementById('main'));
});

The handlers are React components, the simplest possible setup. When the app starts I land on the "company" page as expected. Then when I transition to "employees" all is well, but when I transition back to "company", I observe that an entirely new {Company} component is created, thus blowing away my state. This is going to result in many unecessary API calls, unless I'm doing something wrong or not understanding.

Is there a way to tell the Route to use an existing handler if one exists and just re-render it? Instead of creating a new class?

blackwood
  • 362
  • 3
  • 12

1 Answers1

0

Keeping the state in a flux store

One solution for you would be to keep the state in a flux store. When the component is mounted, request data from the store in the getInitialState() function.

Keeping the state in a parent component

If you do not want to use a flux store (because it increases the complexity of your simple example), I recommend keeping the state in a parent component, and passing it to your as a prop.

Of course, this would only work if your parent component does not become unmounted. I believe that the root component <Handler /> in your example should stay mounted between state transitions in your example.

I recommend that you look at this tutorial that goes over how to pass props to a child component.

This tutorial goes over how to communicate to the parent from the child.

Desmond Lee
  • 707
  • 6
  • 17
  • I am storing state in a flux store. That is not the issue. The issue is that getInitialState is being called multiple times. I need it to be called only once. – blackwood Mar 03 '15 at 14:58
  • It shouldn't mater that `getInitialState` is being called multiple times if you get the initial state from the value stored in the store. If you don't want to make too many API calls, avoid making an API call to fetch the data in `getInitialState` if the data is already present in the store. – Desmond Lee Mar 03 '15 at 15:29
  • If your problem is more complicated than that, can you provide a sample of what you're trying to do? [JSFiddle](http://jsfiddle.net/vjeux/kb3gN/) is a good tool for that. – Desmond Lee Mar 03 '15 at 15:36