๐Ÿคท๐Ÿปโ€โ™€๏ธ Redux?

ohwowo_oยท2023๋…„ 1์›” 7์ผ
0

๋ฆฌ๋•์Šค๋ฅผ ํ•œ๋ฒˆ ์ •๋ฆฌํ•œ ์ ์ด ์žˆ๋Š” ํŒ€ํ”„๋กœ์ ํŠธ๋ฅผ ์ค€๋น„ํ•˜๋ฉด์„œ
๋‹ค์‹œํ•œ๋ฒˆ ๋” ๊ผผ๊ผผํžˆ ๊ฐœ๋… ์ •๋ฆฌ๋ฅผ ํ•˜๊ธฐ์œ„ํ•ด ์•Œ์•„๋ณด์ž โ™ช( 'ฯ‰' ูˆ(ูˆ"

Redux๋ฅผ ์“ฐ๋Š” ์ด์œ 
1. props ๋ฌธ๋ฒ• ๊ท€์ฐฎ์„ ๋•Œ
2. state ๋ณ€๊ฒฝ ๊ด€๋ฆฌ ํ•  ๋•Œ

redux๋ฅผ ์„ค์น˜ํ•˜๋ฉด state๋ฅผ ๋ณด๊ด€ํ•˜๋Š” ๋ณด๊ด€ํ•จ์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฑฐ์ž„

Reducer
์ƒํƒœ๊ด€๋ฆฌ๋ฅผ ๋‹ด๋‹นํ•˜๋Š” Hook
useState๋ฅผ ํ†ตํ•œ ์ƒํƒœ ๊ด€๋ฆฌ ๋ฐ ๋ฐ์ดํ„ฐ ์ถ”๊ฐ€ / ์ œ๊ฑฐ / ์ˆ˜์ • ๋“ฑ์˜ ๊ฐ์ข… Handler๋ฅผ ํ•˜๋‚˜์˜ ํ•จ์ˆ˜๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ด์คŒ

const [state, dispatch] = useReducer(๋ฆฌ๋“€์„œ ์ด๋ฆ„, ์ดˆ๊ธฐ ๋ฐ์ดํ„ฐ)
export function userReducer(state, action){
	switch (action.type){
    	case 'ADD':
        	return [...state, action.data]
        case 'REMOVE':
        	return ~~~
        default:
        	throw new Error(`Unhandled action type : ${action.type}`)
    }
}
//state๋Š” ๋ง๊ทธ๋Œ€๋กœ ํ˜„์žฌ ์ƒํƒœ๊ฐ’,
//action์€ dispatch ํ•จ์ˆ˜ ์‹คํ–‰ ์‹œ ์ธ์ž๋กœ ๋„ฃ์–ด์ค€ ๊ทธ ๊ฐ’์„ ๋งํ•ฉ๋‹ˆ๋‹ค
//๊ทธ๋ž˜์„œ type:ADD๋ผ๊ณ  ์ธ์ž์— ๋ช…์‹œํ•˜๋ฉด action.type์„ ํ†ตํ•ด์„œ ๊ทธ ๊ฐ’์„ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๊ฒŒ ๋จ
//dispatch({type: 'ADD'}) -> action = {type: 'ADD'}

์ปดํฌ๋„ŒํŠธ์—์„œ state ์ˆ˜์ •์š”์ฒญํ•˜๋ ค๋ฉด? dispatch ์“ฐ๋ฉด๋จ

์„ค์น˜๋ฐฉ๋ฒ•
yarn add redux react-redux

์„ธํŒ…๋ฐฉ๋ฒ•
import {Provider} from 'react-redux';
<Provider> </Provider>์›ํ•˜๋Š” ๊ณณ ๊ฐ์‹ธ๊ธฐ
๊ฐ์‹ธ์ง„ ๋ถ€๋ถ„์€ props์—†์ด๋„ state ๊ณต์œ ๊ฐ€๋Šฅ
import {createStore} from 'redux';
let store = createStore(()=>{return [{id:0, name:'๋ฉ‹์ง„์‹ ๋ฐœ', quan:2}]});

  • ์ปดํฌ๋„ŒํŠธ์—์„œ store์— ์žˆ๋Š” state์“ฐ๋ ค๋ฉด
import {connect} from 'react-redux';
  1. function๋งŒ๋“ค๊ธฐ
function ํ•จ์ˆ˜๋ช…(state){ //state๋ฅผ propsํ™”์‹œํ‚ด
  return {
    state : state
  }
}
  1. export default connect()()
export default connect(ํ•จ์ˆ˜๋ช…)(App)
  1. store ๋ฐ์ดํ„ฐ๋ฅผ props๋กœ ๋“ฑ๋กํ•˜๊ธฐ
function App (props) {
  return (
    <div>
      <div>{props.state[0].name}</div>
    </div>
  );
};

0๊ฐœ์˜ ๋Œ“๊ธ€