Reputation: 647
I'm building a react app, I use Redux to manage the state and react router v4 for routing. I use webpack as module bundler. And it has this structure.
-Wrapper
-Home /
-Homepage /h
--GalleryContainer /h/gallery
---Gallery /h/gallery
---Item /h/gallery/:itemId
--About /h/about
--Links /h/links
I'm at Item
component, where I would render only the element that matches itemId
. when I first click to display, it doesn't render unless I refresh and in some cases renders an error of module not found (for picture) but render if I refresh the page. The rendering works fine on other components, but not on this one where matching params is necessary for displaying the appropriate props.
Any input or help into the right direction would be appreciated.
import React from 'react'
class Item extends React.Component {
render() {
const item=this.props.items[this.props.match.params.itemId]
return (
<div>
<h1> {item.title} </h1>
</div>
)
}
}
export default Item
Edit: The props passed from connect component displays normally in Item
component, like if I console.log(this.props.items)
it displays after clicking. but once they're conditioned by custom params const item=this.props.items[this.props.match.params.itemId]
, I get this problem.
Adding GalleryContainer routes
<div>
<Route path={`${this.props.match.path}`}
exact render={(props)=><Gallery
gallery={this.props.gallery}
{...props} />} />
<Route path={`${this.props.match.path}/:itemId`}
render={(props)=><Item
gallery={this.props.gallery}
item={this.props.items} {...props} />} />
</div>
If there is another components to post to clarify this issue, let me know.
Solution It finally worked. It turns out that I added a space in
<Link to={`h/portfolio/${pod.code}`}>
which explains the error at rendering at first time.
Upvotes: 0
Views: 202
Reputation: 5243
Try this.
import React from 'react'
class Item extends React.Component {
constructor(props){
super(props);
this.state={item:null};
}
componentWillMount()
{
this.setState({item:this.props.items[this.props.match.params.itemId]});
}
componentWillReceiveProps(nextProps) {
this.setState({item:nextProps.items[nextProps.match.params.itemId]});
}
render() {
let {item} = this.state;
return (
<div>
<h1> item?item.title:""} </h1>
</div>
)
}
}
export default Item
Upvotes: 1