javascript - Reusing react/redux component on different routes connected to different part of state -
i running problem because have complex component renders list of items. list of items taken directly redux state tree. want have 2 separate routes reuse same component, each of them connect different list state tree.
here simplified example:
starting state tree:
state = { fruits: ['apple', 'banana', 'grape', 'pear'], vegetables: ['celery', 'carrot', 'cucumber'] }
and simple listing component
class listview extends component { render() { return ( <div> {this.props.items.map((item, index) => <div key={index}>{item}</div> )} </div> ) } } function mapstatetoprops(state) { return { items: state.fruits } } export default connect(mapstatetoprops)(listview)
the higher level app component looks this:
class app extends component { render() { return ( <div> {this.props.children} </div> ) } } export default connect()(app)
and routes this:
<route path='/' component={app}> <indexredirect to='fruits' /> <route path='fruits' component={listview} /> <route path='vegetables' component={listview} /> </route>
so right listview component connected fruits part of redux state. utilize route structure here '/fruits' , '/vegetables' both use same component, '/fruits' list fruits while '/vegetables' list vegetables.
the obvious work around create new , identical component class , change mapstatetoprops method connect vegetables array.
is there way reuse component have access different parts of state tree in each?
from listview, export both fruitslist , veggieslist separate components, display correct 1 based on route.
class listview extends component { render() { return ( <div> {this.props.items.map((item, index) => <div key={index}>{item}</div> )} </div> ) } } function mapstatetopropsveggies(state) { return { items: state.veggies } } function mapstatetopropsfruits(state) { return { items: state.fruits } } const veggieslist = connect(mapstatetopropsveggies)(listview); const fruitslist = connect(mapstatetopropsfruits)(listview); export default listview; export { veggieslist, fruitslist };
then update router to:
<route path='/' component={app}> <indexredirect to='fruits' /> <route path='fruits' component={fruitslist} /> <route path='vegetables' component={veggieslist} /> </route>