✅ 동적 라우팅 사용하기
✅ 카드를 클릭했을때 해당카드의 디테일 페이지로 이동
✅ 이동하고나서, 바로전 페이지로 이동할 수있는 BackBtn
✅ PrevPros
---Route.js-----
<Router>
<Switch>
<Route exact path="/monsters" component={UrlParameters} />
<Route exact path="/monsters/detail/" component={MonsterDetail} />
<Route exact path="/monsters/detail/:id" component={MonsterDetail} />
</Switch>
</Router>
<Route <Route exact path="/monsters" component={UrlParameters} />
에서 exact path는 정확한 경로를 나타내고, component는 이동시킬 컴포넌트르 작성하면된다.
쉽게말해서 해당 경로로가면 해당컴포넌트로 이동하는것!!
render() {
const {id, name, email} = this.props;
console.log(this.props.id);
return (
<div className="card-container" onClick={this.goToDetail}>
<img src={`https://robohash.org/${id}?set=set2&size=180x180`}></img>
<h2> {name}</h2>
<p> {email}</p>
</div>
);
}
export default withRouter(Card);
{this.props.id}
를 사용하자!this.props.id
는 monster.js에서 필터링된 데이터가 들어있는 id이다. 즉, search에서 입력한 데이터들의 카드만 UI에 표시하고 ID를 맵핑이 돌때마다 할당이되는것이다this.props.id
에 할당되는것이다 (총 3번)----Monster.js------
const {userInput, monsters} = this.state;
const filteredData = monsters.filter((data) => {
return (
data.name.toLocaleLowerCase().includes(userInput.toLocaleLowerCase()) ||
data.email.toLocaleLowerCase().includes(userInput.toLocaleLowerCase())
);
});
return (
<div className="Monsters">
<h1>컴포넌트 재사용 연습!</h1>
<SearchBox handleChange={this.handleChange} />
<CardList monsters={filteredData} />
{/* <SearchBox handleChange=정의한메소드 /> */}
{/* <CardList monsters=몬스터리스트 /> */}
</div>
);
state = {
data: {},
};
getData = () => {
fetch(
`https://-/users/${this.props.match.params.id}`
)
.then((res) => res.json())
.then((res) =>
this.setState({
data: res,
})
);
};
componentDidMount() {
this.getData();
}
this.props.match.params
이다!! 이것을 통해서 monsters/detail이 들어오고http~~/users/monsters/detail.id
이렇게 들어올 수 있는것이다.push(
/monsters/detail/${this.props.id});
를 하게되면 id값이 주소 경로에 뜨고 그경로를 props.match를 통해 id값을 읽어서 id값에 해당되는 data들을 불러올 수있는것이다.
---CardDetail-----
goToDetail = () => {
this.props.history.push(`/monsters/detail/${this.props.id}`);
};
render() {
const {id, name, email} = this.state.data;
return (
<div className="url-parameters">
<div className="btn-wrapper">
<button onClick={this.goToMonstersList}>Back to Monsters List</button>
</div>
<Card id={id} name={name} email={email} />
<div className="btn-wrapper">
<button onClick={this.goToPrevious}>Previous</button>
<button onClick={this.goToNext}>Next</button>
</div>
</div>
);
}
}
goToMonstersList = () => {
this.props.history.push('/');
};
goToPrevious = () => {
this.props.history.push(
`/monsters/detail/${this.props.match.params.id - 1}`
);
};
goToNext = () => {
this.props.history.push(
`/monsters/detail/${+this.props.match.params.id + 1}`
);
};
componentDidUpdate(prevProps, _) {
if (prevProps.match.params.id !== this.props.match.params.id) {
this.getData();
}
}