I have started learned React.js these days.
I am wondering if I can use the useEffect
hook and function component instead of componentDidMount()
and class component, for example, when users go to DIRECTLY "http://localhost:3000/movie-detail" without clicking on "movie" Link.
I tried some way and I think, in this case, I have to use componentDidMount()
and class component because the "Movie" Link must click on to pass props
to the "Details" component.
If you know how to handle this problem can you let me know, please?
Here is my "Movie" component where has a pathname props.
function Movie({id, year, title, summary, poster, genres}){
return (
<Link
to={{
pathname:"/movie-detail",
state: {
year,
title,
summary,
poster,
genres
}
}}
>
<div className="movie">
...
</div>
</Link>
)
}
Here is my "App" component where passes the pathname props to a "Detail" component.
function App() {
return (
<BrowserRouter>
<Navigation />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/movie-detail" component={Detail} />
</Switch>
</BrowserRouter>
)
}
Here is my "Detail" component where gets props the form Route component.
function Detail({location, history}) {
useEffect(() => {
if(location === undefined) {
history.push("/");
}
}, [ location, history])
const { title } = location.state;
return (
<h1>Title: {title}</h1>
)
}
And I got error code like this below.
TypeError: Cannot destructure property 'title' of 'location.state' as it is undefined.