기존에서 부모 요소에서 list 사용
이제 이렇게 하는 게 아니라 (props 가 아닌)
redux를 써보자!
npm 으로 redux와 react-redux 설치
import { useState } from 'react';
import Contact from './Component/Contact';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
export default function App() {
function reducer(state = [], action) {
return state;
}
const store = createStore(reducer);
const [list, setList] = useState([]);
return (
<>
<Provider store={store}>
현재 개수 : {list.length} <br />
<Contact list={list} setList={setList} />
</Provider>
</>
);
}
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
export default function Contact() {
// state에 접근을 위해 훅 사용 (useSelector) 존재하는 state 가져와서 list에 넣겠다는 의미
const list = useSelector((state) => state);
const dispatch = useDispatch();
function writeList() {
var action = {
// 할일 담기, 타입과 담길 값
type: 'ADD',
payload: {
writer: '1',
title: 'a',
},
};
dispatch(action); //담은 개체를 dispatch에 전달한다.
// let form = document.getElementById('form_write');
// let newList = {
// writer: form.writer.value,
// title: form.title.value,
// };
// setList([...list, newList]);
}
return (
<div>
<form id="form_write" style={{ marginBottom: '15px' }}>
<input type="text" name="writer" placeholder="작성자" />
<input type="text" name="title" placeholder="제목" />
<button type="button" onClick={writeList}>
작성
</button>
</form>
<table border={1}>
<thead>
<tr>
<th>번호</th>
<th>제목</th>
<th>작성자</th>
</tr>
</thead>
<tbody>
{list.map((value, i) => {
// value = { writer: ~~ , title~~ };
return (
<tr>
<td>{i + 1}</td>
<td>{value.title}</td>
<td>{value.writer}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
app.js로 가서
배열은 값이 복제가 안되기 때문.
객체나 값은 주소가 들어가기 때문이다
전개연산자 대신 재할당도 가능하다.
import { useState } from 'react';
import Contact from './Component/Contact';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
export default function App() {
function reducer(state = [], action) {
if (action.type === 'ADD') {
return [...state, action.payload];
}
return state;
}
const store = createStore(reducer);
const [list, setList] = useState([]);
return (
<>
<Provider store={store}>
현재 개수 : {list.length} <br />
<Contact />
</Provider>
</>
);
}
리액트는 빌드해서 올려야한다,, (무겁다 앱이)
'[부트캠프] IT 코딩 부트캠프 후기 > [Let's TIL🚴♀️] CodingON' 카테고리의 다른 글
[socket] 소켓 기초, 실습 (0) | 2023.02.07 |
---|---|
[react서버 올리기] 빌드 , 서버 올리기 (0) | 2023.02.02 |
[React] Redux 실습 todolist, mbtitest (0) | 2023.01.19 |
[Redux] REACT (0) | 2023.01.17 |
[React] 백엔드 사용, CSS 만들기, 리액트라우터, 에러처리 (0) | 2023.01.17 |