I am trying to figure out how to pass props to a component matching a certain route. As you can see from the code below, every time a user hits /items/:id
I get the id from the url and hopefully get the right item accessing the array using that id.
<Route exact path="/items/:id" render={(props) => {
let itemId = parseInt(props.location.pathname.replace('/items/', ''));
console.log(this.state.items[itemId].description);
return <ItemDetail item={this.state.items[itemId]} />;
The problem is if I run this code, React will crash returning an angry red cannot read property description of undefined
, but — and that's where I get totally confused — if I try to log this.state.items[itemId]
I get to see the full object in the console. Naturally the exact same thing happens if I pass item
as a prop and try to get the description out of it from the child component ItemDetail
.
You need to now I am currently setting the data in the componentDidMount
lifecycle method with a simple
componentDidMount() {
this.setState({
items: data
});
}
and React breaks but if I change that to the soon to be deprecated componentWillMount
the application runs as it should and I don't understand why. If state has been set after mounting and I know for a fact that the item exists in the array because I can log it, why can't I read the properties inside it?