[Redux] vanillaJS에서 redux 복습

jiseong·2022년 1월 11일
0

T I Learned

목록 보기
165/291

reducer

해당 파일이 실행되면 reducer는 최초로 한번은 실행이 되기 때문에 초기 state 값을 지정해줘야 한다.

const initState = {
  mode: 'WELCOME',
  topics: [
    {id: 1, title:'html', body:'html is ...'},
    {id: 2, title:'css', body:'css is ...'},
    {id: 3, title:'js', body:'js is ...'}
  ],
  id: null
}

function reducer(state = initState, action) {
  console.log('reducer', state, action);

  const newState = {...state};

  switch(action.type){
    case 'CHANGE_MODE':
      newState.mode = action.mode;
      return newState;
    case 'CHANGE_ID':
      newState.mode = action.mode;
      newState.id = action.id;
    default:
      return newState;
  }
}

createStore

redux devtool을 위한 설정과 reducer를 매개변수로 넣는다.

const store = Redux.createStore(
  reducer,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

getState

store의 state에 접근하기 위해 getState() 메서드를 사용해야 한다.

const {topics} = store.getState();
const state = store.getState();
// state에는 mode, topics, id등이 존재

dispatch

store의 state를 변경하기 위해 액션을 사용하며 액션은 dispatch로 전달한다.

// action: {type:'CHANGE_ID', mode: 'READ', id: ${topic.id}}

store.dispatch({type:'CHANGE_ID', mode: 'READ', id: ${topic.id}})

subscribe

state가 변화되면 그 변화를 UI에 적용하기 위해 subscribe를 해야 한다.

store.subscribe(Article);

전체 코드

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/5.0.0-alpha.0/redux.min.js"></script>
    <title>With Redux</title>
</head>
<body>
    <header></header>
    <nav>

    </nav>
    <article>

    </article>
    <script>
        const initState = {
            mode: 'WELCOME',
            topics: [
                {id: 1, title:'html', body:'html is ...'},
                {id: 2, title:'css', body:'css is ...'},
                {id: 3, title:'js', body:'js is ...'}
            ],
            id: null
        }

        const store = Redux.createStore(
            reducer,
            window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
        );
        
        // 실행하면 한번은 무조건 실행
        function reducer(state = initState, action) {
            console.log('reducer', state, action);

            const newState = {...state};

            switch(action.type){
                case 'CHANGE_MODE':
                    newState.mode = action.mode;
                    return newState;
                case 'CHANGE_ID':
                    newState.mode = action.mode;
                    newState.id = action.id;
                default:
                    return newState;
            }
        }

        Header();
        Nav();
        Article();
        store.subscribe(Article);

        function Header(){
            document.querySelector('header').innerHTML = `
                <h1><a href="/">WEB</a></h1>
            `;
        }
        function Nav(){
            const {topics} = store.getState();

            document.querySelector('nav').innerHTML = `
            <ul>
                ${topics.map((topic,idx) => 
                    `<li>
                        <a href="/read/${topic.id}"token interpolation">${topic.id}})
                        ">${topic.title}
                        </a>
                    </li>`
                ).join('')}
            </ul>
            `;
        }
        function Article(){
            const state = store.getState();


            let articleTag = '';
            if(state.mode === 'WELCOME'){
                articleTag = `
                    <h2>Welcome</h2>
                    Hello, React
                `;
            } else if(state.mode === 'READ'){
                const selectedTopic = state.topics.filter(topic => topic.id === state.id);

                if(selectedTopic.length > 0){
                    articleTag = `
                        <h2>${selectedTopic[0].title}</h2>
                        ${selectedTopic[0].body} 
                    `;
                } else {
                    articleTag = `
                        <h2>error</h2>
                    `;
                }
            }

            document.querySelector('article').innerHTML = articleTag;
        }
    </script>
</body>
</html>

0개의 댓글