[React & NodeJS]공부#5

36699 단어 ReactnodejsReact

날짜 : 21.06.25
참고 강의

[React.js]

1. 로그인 페이지

  • LandingPage.js(시작페이지) 수정
import React, { useEffect } from 'react';
import axios from 'axios';

function LandingPage() {

    useEffect(() => {
        axios.get('/api/hello')
            .then(response => console.log(response.data))
    }, []);
    return (
        <div style={{
            display: 'flex', justifyContent: 'center', alignItems: 'center',
            width: '100%', height: '100vh'
        }}>
            <h2>시작 페이지</h2>
        </div>
    )
}

export default LandingPage;
  • [LoginPage.js] retrun 부분 먼저 생성 -> 페이지의 틀
return (
        <div style={{
            display: 'flex', justifyContent: 'center', alignItems: 'center',
            width: '100%', height: '100vh'
        }}>
            <form style={{ display: 'flex', flexDirection: 'column' }}
            >
                <label>Email</label>
                <input type='email' value={} onChange={} />
                <label>Password</label>
                <input type='password' value={} onChange={} />
                <br />
                <button>
                    Login
                </button>
            </form>
        </div>
    )

🔽 결과화면 🔽

  • [LoginPage.js]의 funtion LoginPagestate()에 state 생성
function LoginPage() {
    const [Email, setEmail] = useState("");
    const [Password, setPassword] = useState("");
}
  • 타이핑을 할 때 onChange의 이벤트 발생하여 state 발생 후 value 변경
    -> [LoginPage.js] funtion LoginPagestate()
function LoginPage() {
    const [Email, setEmail] = useState("");
    const [Password, setPassword] = useState("");

    const onEmailHandler = (event) => {
        setEmail(event.currentTarget.value)
    };

    const onPasswordHandler = (event) => {
        setPassword(event.currentTarget.value)
    };
}
  • onSubmitHandler -> 로그인 정보 입력 시 refresh 방지
function LoginPage() {
    const [Email, setEmail] = useState("");
    const [Password, setPassword] = useState("");

    const onEmailHandler = (event) => {
        setEmail(event.currentTarget.value)
    };

    const onPasswordHandler = (event) => {
        setPassword(event.currentTarget.value)
    };
  	const onSubmitHandler = (event) => {
        event.preventDefault(); // 페이지 refresh 방지

        let body = {
            email: Email,
            password: Password,
    };
}
  • [LoginPage.js] return의 value, onChange, onSubmit 수정
...
...
<form style={{ display: 'flex', flexDirection: 'column' }}
                onSubmit={onSubmiHandler}
            >
                <label>Email</label>
                <input type='email' value={Email} onChange={onEmailHandler} />
                <label>Password</label>
                <input type='password' value={Password} onChange={onPasswordHandler} />
                <br />
                <button>
                    Login
                </button>
            </form>
...
...

2. Redux를 사용한 정보 전달

  • [LoginPage.js]에 dispatch를 통해 action 생성
import { useDispatch } from 'react-redux';

function LoginPage{
  ...
  ...
  const dispatch = useDispatch();
    dispatch(loginUser(body))
                .then(response => {
                    if (response.payload.loginSuccess) {
                        props.history.push('/')
                    } else {
                        alert('Error')
                    }
                });
}
  • [_actions]-[user_action.js] 파일 생성
import axios from 'axios';
import {
    LOGIN_USER
} from './types';

export function loginUser(dataToSubmit) {
    const request = axios.post('/api/users/login', dataToSubmit)
        .then(response => response.data)

    return {//reducer로 전송
        type: "LONGIN_USER",
        payload: request,
    }
}
  • [_actions]-[types.js] 파일 생성
export const LOGIN_USER = "login_user";
  • [_reducers]-[user_reducer.js] 파일 생성
import {
    LOGIN_USER
} from '../_actions/types';

export default function (state = {}, action) {
    switch (action.type) {
        case LOGIN_USER:
            return { ...state, loginSuccess: action.payload }
            break;

        default:
            return state;
    }
}
  • [_reducers]-[index.js] 수정
// rootReducer에 Reducer들을 합체
import { combineReducers } from "redux";
import user from './user_reducer';

const rootReducer = combineReducers({
    user,
})

export default rootReducer;
  • [LoginPage.js] 최종 코드
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { loginUser } from '../../../_actions/user_action'

function LoginPage(props) {
    const dispatch = useDispatch();
    const [Email, setEmail] = useState("");
    const [Password, setPassword] = useState("");

    const onEmailHandler = (event) => {
        setEmail(event.currentTarget.value)
    };

    const onPasswordHandler = (event) => {
        setPassword(event.currentTarget.value)
    };

    const onSubmitHandler = (event) => {
        event.preventDefault(); // 페이지 refresh 방지

        let body = {
            email: Email,
            password: Password,
        };

        dispatch(loginUser(body))
            .then(response => {
          // 로그인 성공 시 첫 페이지로 이동
                if (response.payload.loginSuccess) {
                    props.history.push('/')
                } else {
                    alert('Error')
                }
            })

    };

    return (
        <div style={{
            display: 'flex', justifyContent: 'center', alignItems: 'center',
            width: '100%', height: '100vh'
        }}>
            <form style={{ display: 'flex', flexDirection: 'column' }}
                onSubmit={onSubmitHandler}
            >
                <label>Email</label>
                <input type='email' value={Email} onChange={onEmailHandler} />
                <label>Password</label>
                <input type='password' value={Password} onChange={onPasswordHandler} />
                <br />
                <button>
                    Login
                </button>
            </form>
        </div>
    )
}

export default LoginPage
  • redux로 결과 확인

Full Code

Walang Github

Walang Notion

좋은 웹페이지 즐겨찾기