1.상위 컴퍼넌트에 redux combineReducer 활용해주고 createStore 함수에 combineReducer로 묶어줌
//index.js
[..]
import { Provider } from "react-redux";
import { createStore, combineReducers } from "redux";
let alert초기값 = true;
function reducer2(state = alert초기값, 액션) {
if (액션.type === "alert닫기") {
state = false;
return state;
}
return state;
}
let 초기값 = [
{ id: 0, name: "멋진신발", quan: 2 },
{ id: 1, name: "헤진신발", quan: 5 },
];
function reducer(state = 초기값, 액션) {
if (액션.type === "수량증가") {
let copy = [...state];
copy[0].quan++;
return copy;
} else if (액션.type === "수량감소") {
let copy = [...state];
copy[0].quan--;
return copy;
} else {
return state;
}
}
let store = createStore(combineReducers({ reducer, reducer2 }));
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<Provider store={store}>
[...]
2.하위컴퍼넌트에서 새로 생성된 reducer 하단과 같이 표기
**공통된 모듈에서 사용하는 state가 아니면 굳이 redux를 사용할 필요가 없음!!
//Cart.js
[..]
import { connect } from "react-redux";
function Cart(props) {
return (
<div>
<Table striped bordered hover size="sm">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
{props.state.map((a, i) => {
return (
<tr key={i}>
<td>{a.id}</td>
<td>{a.name}</td>
<td>{a.quan}</td>
<td>
<button
onClick={() => {
props.dispatch({ type: "수량증가" });
}}
>
+
</button>
<button
onClick={() => {
props.dispatch({ type: "수량감소" });
}}
>
-
</button>
</td>
</tr>
);
})}
</tbody>
</Table>
{props.alert열렸니 === true ? (
<div className="my-alert2">
<p>지금 구매하시면 신규할인 20%</p>
<button
onClick={() => {
props.dispatch({ type: "alert닫기" });
}}
>
닫기
</button>
</div>
) : null}
</div>
);
}
function state를props화(state) {
return {
state: state.reducer,
alert열렸니: state.reducer2,
};
}
export default connect(state를props화)(Cart);
// export default Cart;
'프론트엔드관련 책예제실습정리 > CO.APP(react)' 카테고리의 다른 글
redux2(redux 설정방법과 활용) (0) | 2021.07.04 |
---|---|
redux 사용이유 1 (복잡한 props 사용하지 않아도됌) (0) | 2021.07.01 |
03-tab만들기까지 예제 (0) | 2021.07.01 |
setTimeout 사용시 주의점 (0) | 2021.07.01 |
useEffect 와 componentDidMount 차이 (0) | 2021.07.01 |