초보자의 React.js (5) - CRUD[UPDATE]

김문범·2020년 5월 26일
0

Beginner-React

목록 보기
5/6
post-thumbnail

이번에는 UPDATE를 작성하겠습니다.
어차피 작성순서는 constants.js -> actions.js -> reducers.js -> Category.js(즉, 작성 중인 components파일을 의미합니다.)

1-1. constants.js는 3편에서 이미 모두 작성했습니다.

1-2. actions.js 추가 부분

export const categoryUpdate = (id, year, semester) => ({
    type: CATE_UPDATE,
    request: {
        url: '/category/update',
        method: 'POST',
        data: {id: id, year: year, semester: semester}
    }
});

1-3. reducers.js 추가 부분

case success(CATE_UPDATE): {
            return {
                ...state,
                lists: state.lists.map(item => item.id === action.data.id ? action.data : item)
            };
        }

"map"이라는 자바스크립트 프로토타입으로 lists의 id와 돌아온 action.data의 id와 같으면 action.data를 주입하여 같은 id의 값을 교체하는 방식입니다.
즉, 업데이트 시 보낸 값들이 확인이 되고 처리가 완료되면 다시 돌아와 기존의 lists와 비교하여 자신의 id값과 같은 자리에 데이터가 교체되는 것입니다.

1-4. Categort.js 추가 부분

// import
import {categoryRead, categoryInsert, categoryUpdate} from "../store/category/actions";

// render
<div>
                <table border={'1'} width={'200'} cellSpacing={'0'}>
                    <thead>
                    <tr>
                        <th>학년</th>
                        <th>학기</th>
                    </tr>
                    </thead>
                    <tbody>
                    {/* javascript의 프로토타입 map으로 반복문으로 생각하면 편함. */}
                    {this.props.lists.map(item => (
                        <tr key={item.id} onClick={function () {
                            this.setState({id: item.id, year: item.year, semester: item.semester});
                            document.querySelector('#year').value = item.year;
                            document.querySelector('#semester').value = item.semester;
                        }.bind(this)}>
                            <td>{item.year}</td>
                            <td>{item.semester}</td>
                        </tr>
                    ))}
                    </tbody>
                </table>
                <hr/>
                <div>
                    <input type="text" id={'year'} placeholder={'학년'} onChange={function (e) {
                        this.setState({year: e.target.value});
                    }.bind(this)}/>
                    <br/>
                    <br/>
                    <input type="text" id={'semester'} placeholder={'학기'} onChange={function (e) {
                        this.setState({semester: e.target.value});
                    }.bind(this)}/>
                </div>
                <hr/>
                <div>
                    <button onClick={function () {
                        this.props.categoryInsert(this.state.year, this.state.semester);
                    }.bind(this)}>CREATE
                    </button>
                    <button onClick={function () {
                        this.props.categoryUpdate(this.state.id, this.state.year, this.state.semester);
                    }.bind(this)}>UPDATE
                    </button>
                </div>
            </div>

// action                    
const mapDispatchToProps = dispatch => ({
    categoryRead: () => dispatch(categoryRead()),
    categoryInsert: (year, semester) => dispatch(categoryInsert(year, semester)),
    categoryUpdate: (id, year, semester) => dispatch(categoryUpdate(id, year, semester)),
});

테이블 tr에 onClick으로 state값과 각각의 input박스로 값을 보내어 수정이 가능하도록 합니다.
여기서 id 또는 semester 둘 중 하나만 수정하는 경우 setState로 state값을 주지 않는다면 해당 필드값이 없어서 오류가 발생합니다.

이상으로 UPDATE에 대해서는 마치겠습니다.

profile
다양하지만 공부할 것이 많은 개발자입니다.

0개의 댓글