简体   繁体   中英

Designing state for Reusable React Components and Browser history

I'm looking for ways to structure state in my React components so that I can accomplish two goals together: (1) managing browser history in a complex app, and (2) letting individual components be easily reusable in environments outside the main app.

The app has a Panel component which lets users navigate and read content on our site. In the main app, multiple panels can be opened and arranged together. Outside of the main app, there are other pages where I'd just like to be able to easily drop in a single Panel component.

As this code has developed so far, each Panel has a rich state representing what content it has loaded and other display settings. This makes it easy to drop in to another page - I can just render a Panel component and the user can interact with it and it takes care of itself.

For browser history however, this is getting hairy. There is an App component which manages multiple Panels and the states pushed to and popped from history. In order for it to have a complete picture of the state of the whole app, each panel pushes up a copy of its state when changes occur. When state is popped from the history that App component can pass down an initialState from each of the Panels it renders. As you can imagine, this is getting messy and error prone with the cycles of updates that end up looping back to each other.

It feels like the approach I need to take is to Centralize State (a la the recommendation here ) and try to make each individual Panel stateless. Since it will be a significant effort to rewrite all the calls to setState already in the code, I'm trying to evaluate if this is the only way to go. It also feels like this approach will make it harder to reuse the components outside the app. I'll lose the feeling that a Panel is a self-contained component which I can just render on a page, since it will need some kind of outside manager as well to handle its state and all the events that change it from within.

What would you recommend?

I made a application on react and implementing react-router you can pass throw the URL data to every panel know in what state are and what content is loaded, by example you can have an url like: http://yoururl.com/index/user/userID1/item/itemID2/filterDate?= "19/09/2014"

To reuse your panels you can made a url that made an herarchical route view: You can pass throw components everything you want to know on the render wich view you have to load.

My routerDomExample

I recommend to investigate react-router.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM