๐ŸคRedux - Part 2. React + Redux (6)

1. Detail ์ปดํฌ๋„ŒํŠธ ๋งŒ๋“ค๊ธฐ

const Detail = () => {
  return <h1>Detail</h1>
}

App.js ์— ์•„๋ž˜์™€ ๊ฐ™์€ ๊ฒฝ๋กœ๋กœ ์—ฐ๊ฒฐํ–ˆ์„ ์‹œ Detail ์ปดํฌ๋„ŒํŠธ๋กœ ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๊ฒŒ props ๋ฅผ ๋‚ด๋ฆฐ ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

<Router>
  <Route path="/" exact component={Home}></Route>
  <Route path="/:id" exact component={Detail}></Route>
</Router>
import { Link } from "react-router-dom";

..... ์ดํ•˜ ์ค‘๋žต .....

return (
  <li>
    <Link to={`/${props.id}`}>
      {props.text} <button onClick={props.onBtnClick}>DEL</button>
    </Link>
  </li>
)

๊ธฐ์กด์˜ li ํƒœ๊ทธ ๋‚ด ์ปจํ…์ธ ๋ฅผ Link ๋กœ ๋ฌถ๊ณ  to ์†์„ฑ์— props.id ๋กœ ๊ฒฝ๋กœ๋ฅผ ์ด๋™ํ•˜๋ฉด ํ•ด๋‹น id ์˜ Detail ์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ด ์ค€๋‹ค.

3. Detail.js ์—์„œ id ๋ฅผ ๋ฐ›์•„์˜ค๋Š” ๋ฐฉ๋ฒ• - useParams

import { useParams } from 'react-router-dom'

const Detail = () => {
  // useParams hooks ๋ฅผ ์‚ฌ์šฉํ–ˆ์„ ๋•Œ id ๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ๋ฒ•
  const id = useParams()
  console.log(id) // {id: "1610867080250"}

  return <h1>Detail</h1>
}

useParams hooks ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ•ด๋‹น ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ ‘๊ทผํ•œ Detail ์˜ id ๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค.

ํ•˜์ง€๋งŒ Redux ๋กœ๋Š” ์–ด๋–ป๊ฒŒ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ์„๊นŒ?

4. Detail.js ์—์„œ id ๋ฅผ ๋ฐ›์•„์˜ค๋Š” ๋ฐฉ๋ฒ• - mapStateToProps

ownProps ๋งŒ์œผ๋กœ๋„ id ๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค.

const mapStateToProps = (state, ownProps) => {
  console.log(ownProps)
}

export default connect(mapStateToProps, null)(Detail)

console1

ownProps ๊ฐ€ ์ฐํžˆ๋Š”๋ฐ ์ด์ œ ๊ฑฐ๊ธฐ์—์„œ match.params.id ๊ฐ€ ํ•„์š”ํ•˜๋‹ค.

const mapStateToProps = (state, ownProps) => {
  console.log(ownProps)
  const {
    match: {
      params: { id },
    },
  } = ownProps
}

์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ownProps.match.params.id ๋กœ ์ ์„ ํ•„์š” ์—†์ด ๋ฐ”๋กœ id ๋กœ ์ ‘๊ทผํ•  ์ˆ˜๊ฐ€ ์žˆ๊ฒŒ ๋œ๋‹ค.

๊ทธ๋ฆฌ๊ณ  ๋ฆฌํ„ด์„ ํ•ด์ฃผ๋ฉด์„œ ํ•ด๋‹น ๊ฐ์ฒด ๋‚ด์— state ๋ฅผ ๋ถˆ๋Ÿฌ์™€์„œ find ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ๋ฐฐ์—ด ๋‚ด toDo ์˜ id ์™€,

ownProps.match.params.id ๊ฐ€ ๊ฐ™์€ ์š”์†Œ ํ•˜๋‚˜๋ฅผ ๋ฆฌํ„ดํ•˜๊ฒŒ ํ•œ๋‹ค.

const mapStateToProps = (state, ownProps) => {
  console.log(ownProps)
  const {
    match: {
      params: { id },
    },
  } = ownProps
  return { toDo: state.find(toDo => toDo.id === parseInt(id)) }
}

Detail ์ปดํฌ๋„ŒํŠธ์—์„œ props ๋กœ ๋ฐ›์•„ ์ฝ˜์†” ๋กœ๊ทธ๋ฅผ ํ™•์ธํ•ด ๋ณด๋ฉด,

console2

์œ„์˜ ๊ทธ๋ฆผ๊ณผ ๊ฐ™์€ ๋ชจ์Šต์„ ํ™•์ธํ•  ์ˆ˜๊ฐ€ ์žˆ๋‹ค.

5. Detail ์ปดํฌ๋„ŒํŠธ ๋ Œ๋” ํ•˜๊ธฐ

const Detail = props => {
  console.log(props)
  return (
    <>
      <h1>{props.toDo?.text}</h1>
      <h5>Created at : {props.toDo?.id}</h5>
      {/* ์™œ ๋ฌผ์Œํ‘œ๋ฅผ ๋ถ™์—ฌ์•ผ ์—๋Ÿฌ๋ฅผ ํ”ผํ•˜๋Š”์ง€๋Š” ์•„์ง ์ž˜ ๋ชจ๋ฅด๊ฒ ๋‹ค. */}
    </>
  )
}

Written by@[DotoriMook]
ํ”„๋ก ํŠธ์—”๋“œ ์ฃผ๋‹ˆ์–ด ๊ฐœ๋ฐœ์ž ๋„ํ† ๋ฆฌ๋ฌต์˜ ๊ธฐ์ˆ ๊ฐœ๋ฐœ ๋ธ”๋กœ๊ทธ ์ž…๋‹ˆ๋‹ค.

GitHubMediumTwitterFacebook