react Redux
Redux(์)๐
npm install redux react-redux
redux๋ฅผ ์ฌ์ฉํ๊ธฐ ์ํด ํฐ๋ฏธ๋์์ ๋ช ๋ น์ด๋ฅผ ํตํด ์ค์นํ์.
๊ธฐ์ด ๋ฌธ๋ฒ๐ฉ
index.js
import { Provider } from "react-redux";
import { createStore } from "redux";
let store = createStore(reducer); //state๋ง๋ค๊ธฐ
function reducer() {
return [
{ id: 0, name: "์ ๋ฐ", quan: 7 },
{ id: 1, name: "์์", quan: 18 },
];
}
ReactDOM.render(
<Provider store={store} >
<App />
</Provider>
);
App.js
import React from "react";
import { connect } from "react-redux";
function Abcd(props) {
return (
<div>
{props.์๋ช
} // ['a','b']
</div>
)
}
function ์๋ช
1(state) {
return {
์๋ช
: state
}
}
export default connect(state)(์๋ช
1);
โ์ด๊ธฐ์ ํ โ
a,b๊ฐ ๋ด๊ธด store์ ์ด๋์์๋ ์ฌ์ฉํ ์ ์๋ค.
index.js
let datastate = [
{ id: 0, name: "์ ๋ฐ", quan: 2 },
{ id: 1, name: "์์", quan: 18 },
];
function reducer(state = datastate, action) {
if (action.type === "inc") {
let copy = [...state];
copy[0].quan++;
return copy;
} else if (action.type === "dec") {
let copy = [...state];
copy[0].quan--;
return copy;
} else return state;
}
let store = createStore(reducer);
App.js
function Cart(props) {
return(
{props.dispatch({ type: "inc" }}
)
โRedux์ ๋ณ์์ ๊ฐ ๋ณ๊ฒฝโ
๋ณ์์ ๊ฐ์ ๋ณ๊ฒฝํ๊ณ ์ถ์๋ ์ด๊ธฐ์ค์ ํ๋ ๊ณณ์์ ๋ณ๊ฒฝํ ์ก์ ์ ๋ง๋ค๊ณ ์๋ช ํ๋ค.
๊ทธ๊ฒ์ ํ์ํ ๊ณณ๋ง๋ค ๋ถ๋ฌ์ค๋ ์์ผ๋ก ๋ณ์์ ๊ฐ์ ๋ณ๊ฒฝํ๋๋ฐ ์ด ๋ฐฉ๋ฒ์ ์ปดํฌ๋ํธ๊ฐ ๋ง์๋ ์๋ฌ๋ฅผ ์ก๊ธฐ์ ์์ฃผ ํธ๋ฆฌํ๋ค.
index.js
function reducer(state = datastate, action) {}
function reducer2(state = opneclose, action) {}
let store = createStore(combineReducers({ reducer, reducer2 }));
app.js
function state(state) {
return {
a: state.reducer,
b: state.reducer2,
};
}
export default connect(state)(Cart);
โ2๊ฐ์ด์์ Reducer๋ง๋ค๊ธฐโ
๋ณ์๋ฅผ ํ๊ฐ๋ ๋ง๋ค๊ณ ์ถ๋ค๋ฉด combineReducers๋ฅผ ํตํด ๋ ๋ง๋ค ์ ์๋ค.