거북이개발자

[Redux] Redux이용한 CRUD구현(Create) 본문

Redux

[Redux] Redux이용한 CRUD구현(Create)

류정식 2021. 2. 9. 17:24

0. 배경

 

 

위의 사진처럼 각각의 성분을 읽고, 만들고, 지울 수 있는 기능을 Redux를 이용해서 만들 생각이다.

 

 

 

 

1. create클릭 시 본문 변경

<li><a onclick="
            event.preventDefault();
            store.dispatch({
                type:'CHANGE_MODE',
                mode:'create'
            })
        " href="/create">create</a></li>

우선 onclick을 이용해준다. dispatch를 이용하여 type, mode를 변경해준다.

 

 if(state.mode === 'create'){
        document.querySelector('#content').innerHTML = `
        <article>
            <form onsubmit="
                event.preventDefault();
                var _title = this.title.value;
                var _desc = this.desc.value;
                store.dispatch({
                    type:'CREATE',
                    title:_title,
                    desc:_desc
                })
            ">
                <p>
                    <input type="text" name="title" placeholder="title">
                </p>
                <p>
                    <textarea name="desc" placeholder="description"></textarea>
                </p>
                <p>
                    <input type="submit">
                </p>
            </form>
        </article>
        `
    }

onsubmit를 통해서 각각의 입력된 값을 dispatch를 통해 store에 저장한다.

 

 

 

2. create값 push, 

 else if(action.type === 'CREATE'){
        var newMaxId = state.max_id + 1;
        var newContents = state.contents.concat();
        newContents.push({id:newMaxId, title:action.title, desc:action.desc});
        newState = Object.assign({}, state, {
            max_id:newMaxId,
            contents:newContents,
            mode:'read'
        })
    }

push 한 값을 newState에 넣어준 뒤 newState를 리턴한다.

store.subscribe(TOC);

그 후 subscribe를 이용해서 추가한 값을 UI에 표시해준다.

'Redux' 카테고리의 다른 글

[Redux] Redux기초 프로그래밍  (0) 2021.02.21
[Redux] Redux이용한 CRUD구현(Delete)  (0) 2021.02.09
[Redux] Redux이용한 CRUD구현(Read)  (0) 2021.02.09
[Redux] Redux의 장점  (0) 2021.02.09
[Redux] 작동 방식  (0) 2021.02.08
Comments