I have this routes:
App.js
...
<Switch>
<Route exact path="/" component={Projects}/>
<Route exact path="/projects/:folder?" component={Projects}/>
<Route exact path="/projects/:folder/:id" component={Sketch}/>
<Route exact path="/projects/:folder/:id/details" component={Details}/>
<Route component={NoMatch}/>
</Switch>
...
I need to fetch data in the Projects page based on the folder param. I retrieve data correctly but it's not rendered. It renders the old list and the state changes. I tried like that:
Projects.js
render () {
return (
...
<Section>
{this.state.projects}
</Section>
...
)
}
componentWillReceiveProps (newProps) {
var params = newProps.match.params;
this.setState({ folder: params.folder })
this.loadProjects();
}
componentDidMount() {
this.setState({ folder: this.props.match.params.folder });
this.loadProjects();
}
loadProjects () {
const url = '/sketches' + (this.state.folder === 'sketches'? '':'/'+this.state.folder) + '/projects.json';
axios.get(url).then((res) => {
if (res.data !== null)
{
const folder = this.state.folder === 'sketches' ? '': this.state.folder
this.setState({
projects: <Grid list={res.data} folder={folder} key={"grid"}/>
});
}
}).catch((ex) => {
console.log(ex);
this.setState({
projects: <Redirect to="NoMatch"/>
});
})
}
I change params with a Link. I don't think is here the error, but I still put this code for you.
...I hope isn't here, because i passed all the time to check elsewhere.
render () {
return (
<Link to={this.state.url}>
{this.props.item.name}
</Link>
)
}
componentDidMount () {
var url = '/projects/' + this.props.item.name + '';
if (!this.props.item.items) {
url = '/projects/' + (this.props.folder || 'sketches') + '/' + this.props.item.name + '/details';
}
this.setState({ url })
}
I'm not using redux as you can see from this code.
const folder = this.state.folder === 'sketches' ? '': this.state.foldercomponentWillReceivePropsbecause you're not going to want to do an api call on every render, only when the props change.