学習[react&NodeJS]#5


日付: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]再試行部分->ページ上のフレームワーク
  • 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]の関数LoginPageState()にステータスを作成
    function LoginPage() {
        const [Email, setEmail] = useState("");
        const [Password, setPassword] = useState("");
    }
  • を入力するとonChangeイベントが発生し、ステータスが発生した後に値が変更されます.
    -> [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->ログイン情報入力時のリフレッシュ防止
  • 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]戻り値、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で動作
  • を作成する.
    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')
                        }
                    });
    }
  • [action]-作成ファイル
  • [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,
        }
    }
  • [action]-作成ファイル
  • [type.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
    
    検査結果は

    Full Code


    Walang Github


    Walang Notion