Hey,
I’m just moved to React and try to do my common Blaze (ViewModel) pattern. I have a layout with 3 sub components that could change the state of the layout component, it depends f.e. on the url. For the reactive variables I’m using Tracker.Component
. Now this is my code:
layout.jsx
export class Layout extends Tracker.Component {
constructor(props) {
super(props);
this.state = {
category: null,
posting: null,
};
}
render() {
return (
<div id="layout">
<div className="bg-1"></div>
<div className="content-box white z-depth-1">
<div id="start">
<CategoriesList layout={this}/>
<Postings layout={this}/>
<Chat layout={this}/>
</div>
</div>
</div>);
}
};
The CateoriesList is the component that lists all categories
CategoriesList.jsx
export class CategoriesList extends Tracker.Component {
constructor(props) {
super(props);
this.state = {
categories: []
};
this.autorun(() => {
this.setState({
categories: Category.find({parent: {$exists: false}}).fetch()
})
});
}
render() {
return (
<div className="s s1 deep-purple accent-1">
<div className="head deep-purple lighten-1">
<h5>Kategorien</h5>
</div>
<div className="categories">
{this.state.categories.map(category => <CategorieList layout={this.props.layout} mainCategory={category} key={category.id}/>)}
</div>
</div>
)
}
}
…and finally I have the component for every single category:
CategorieList.jsx
export class CategorieList extends Tracker.Component {
constructor(props) {
super(props);
this.state = {
subCats: [],
};
this.autorun(() => {
this.setState({
subCats: this.props.mainCategory.getSubs().fetch(),
urlCategory: FlowRouter.getParam("catName")
});
});
this.autorun(() => {
if(this.props.mainCategory.id == this.state.urlCategory) {
this.props.layout.setState({category:this.props.mainCategory.id});
}
});
}
genMeta(cat) {
if(this.state.urlCategory == cat.id) {
return (<Helmet title={cat.name}/>)
}
}
render() {
return (
<div className="category-list deep-purple darken-1">
{this.genMeta(this.props.mainCategory)}
<a href={"/kategorie/"+this.props.mainCategory.id} className="parent">{this.props.mainCategory.name}</a> <span className="new badge">2</span>
<ul>
{this.state.subCats.map((cat) => {
return <li key={cat.id}><a href={"/kategorie/"+cat.id}>{cat.name}</a> {this.genMeta(cat)}</li>;
})}
</ul>
</div>
);
}
};
This is what should happen: If a user visits /category/about
the CategoryList component should set the state of the layout to the current category. I’m getting the error, that the state of another component can’t be set within render or a concstructor, ending in an infinite loop. So my question is now: What is the recommended pattern for this?