ログイン機能の実装
1. /components/view/LoginPage/LoginPage.js
import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { loginUser } from "../../../_actions/user_actions";
function LoginPage(props) {
const dispatch = useDispatch();
// email을 위한 state
const [Email, setEmail] = useState("");
// password를 위한 state
const [Password, setPassword] = useState("");
// input의 내용을 입력할 수 있게
const onEmailHandler = (event) => {
setEmail(event.target.value);
};
const onPasswordHandler = (event) => {
setPassword(event.target.value);
};
const onSubmitHandler = (event) => {
// 새로고침을 막아주기 위해
event.preventDefault();
//console.log(`email: ${Email}`);
//console.log(`password: ${Password}`)
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 type="submit">Login</button>
</form>
</div>
);
}
export default LoginPage;
2. /_actions/types.js
export const LOGIN_USER = "login_user";
3. /actions/user_actions.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 {
type: LOGIN_USER,
payload: request
}
}
4. /_reducers/user_reducers.js
import { LOGIN_USER } from "../_actions/types";
// eslint-disable-next-line import/no-anonymous-default-export
export default function (state={}, action) {
switch (action.type) {
case LOGIN_USER:
return {...state, loginSuccess: action.payload}
default:
return state;
}
}
5. /_reducers/index.js
import { combineReducers} from 'redux';
import user from './user_reducer';
//import comment from './comment_rducer';
const rootReducer = combineReducers({
user
})
export default rootReducer;
Reference
この問題について(ログイン機能の実装), 我々は、より多くの情報をここで見つけました https://velog.io/@dev_shu/로그인-기능-구현テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol