반응형
front 마무리
get 말고 post ~ 등도 추가하기
api.jsx
/*
비동기통신에 대한 내용을 넣는공간
*/
// READ 댓글 읽기
export const getComment = async (dispatch) => {
dispatch({type:'GET_COMMENT'})
try{
let response = await fetch('http://3.19.244.113/api/comment')
let data = await response.json()
let result = data.map(obj=>{
return{...obj, date:obj.updatedAt.substr(0,10)}
})
dispatch({type:'GET_COMMENT_SUCCESS',payload:result})
} catch (e) {
dispatch({ type:'GET_COMMENT_ERROR',payload:e })
}
}
// CREATE 댓글 쓰기
export const postComment = async (dispatch) =>{
dispatch({type:'POST_COMMENT'})
try{
// js 비동기로 통신할 수 있는 객체 fetch
let option = {
method:'POST',
header:{
'Content-type':'application/json; charset=utf-8', // 한글도 받기 (혹시 몰라서!)
},
body:JSON.stringify({userid:'idddd',content:'contentt'})
}
let response = await fetch('http://3.19.244.113/api/comment', options)
//내가 원하는 body값만 받기
let data = await response.json()
dispatch({type:'POST_COMMENT_SUCCESS', payload:data})
}catch(e){
dispatch({type:'POST_COMMENT_ERROR', payload:e})
}
}
// UPDATE 댓글 수정
export const patchComment = async (dispatch) =>{
}
// DELETE 댓글 삭제
export const deleteComment = async (dispatch) =>{
}
commentForm
import React,{useContext,useState} from 'react'
import Store from './Store/context'
import {postComment} from './api/api' //추가
const CommentForm = () => {
const [input,setInput] = useState('')
const {state,dispatch} = useContext(Store)
const handleChange = e => {
const {value} = {...e.target}
setInput(value)
}
const handleSubmit = e => {
e.preventDefault()
//dispatch({ type:'CREATE' ,payload:{userid:'web7722',content:input,date:'2021-07-14'} })
postComment(dispatch,{userid:'eeeee', content:input})
setInput('')
}
return (
<>
<li className="comment-form">
<form onSubmit={handleSubmit}>
<span className="ps_box">
<input
type="text"
api 다시 수정
// CREATE 댓글 쓰기
export const postComment = async (dispatch, body) =>{
dispatch({type:'POST_COMMENT'})
try{
// js 비동기로 통신할 수 있는 객체 fetch
let option = {
method:'POST',
header:{
'Content-type':'application/json; charset=utf-8', // 한글도 받기 (혹시 몰라서!)
},
body:JSON.stringify(body) // CommentForm에서 받은 body 추가
}
let response = await fetch('http://3.19.244.113/api/comment', options)
//내가 원하는 body값만 받기
let data = await response.json()
dispatch({type:'POST_COMMENT_SUCCESS', payload:data})
}catch(e){
dispatch({type:'POST_COMMENT_ERROR', payload:e})
}
}
reducer
// reducer는 결국 상태를 바꿔야 하기떄문에
// 이전 상태값을 가져와야함.
// dispatch 바꿀정보를 받아야함 -> action
// 결국 앤 리턴을해주는데 무엇을 리턴하냐 state값
const reducer = (state, action) => {
switch (action.type) {
case "GET_COMMENT": // 최초 실행하였을때.
console.log('GET_COMMENT')
return {
...state,
loadding: true,
}
case "GET_COMMENT_SUCCESS": //데이터를 완전히 받아왔을때.
console.log('GET_COMMENT_SUCCESS')
return {
...state,
loadding: false,
commentItem: action.payload,
}
case "GET_COMMENT_ERROR": // 데이터를 읽어오지 못했을때.
return {
...state,
loadding: false,
error: action.payload
}
case "CREATE":
return {
...state,
commentItem: [...state.commentItem, action.payload]
}
case "POST_COMMENT":
return {
...state,
//commentItem: [...state.commentItem, action.payload]
}
case "POST_COMMENT_SUCCESS":
return {
...state,
commentItem: [...state.commentItem, action.payload]
}
case "POST_COMMENT_ERROR":
return {
...state,
// commentItem: [...state.commentItem, action.payload]
}
case "UPDATE":
console.log('수정을할거니 ? : ', action)
// let content = action.payload.content;
// let index = action.payload.index;
// let {content,index} = {...action.payload}
// // let {payload:{content,index}} = action
// let {commentItem} = {...state}
// commentItem[index].content = content
// return {
// ...state,
// commentItem:[...commentItem]
// }
let content = action.payload.content;
let index = action.payload.index;
let commentItem = state.commentItem // 복사해서 가져온다. point
console.log(commentItem)
console.log(commentItem[index]) // index값이 무엇을 의미하는지
console.log(commentItem[index].content) // 여기서쓰는 content
console.log(content) // 여기서 쓰는 content
commentItem[index].content = content
console.log('test ', { ...state, commentItem })
return {
...state,
}
//return state
case "DELETE":
console.log('인덱스야 왔니? : ', action.payload);
let newArr = []
//for(let i=0; i<state.commentItem.length; i++){
// if(i !== action.payload) newArr.push(state.commentItem[i])
//}
console.log(newArr, state.commentItem)
// newArr = 내가 원하는값을 삭제하고 남은 배열값
// state.commentITtem = 내가 기존에 가지고있었떤 배열값
// (3) [{…}, {…}, {…}] (4) [{…}, {…}, {…}, {…}]
return {
...state,
//commentItem:[newArr]
commentItem: [...state.commentItem.filter((v, k) => action.payload !== k)]
}
default:
return state
}
}
export default reducer
근데 왜 댓글 추가가 안되는고지,,,,,,,,,
-> 교수님 코드
리액트 긴급 점검.,,,
기본 react html 준비 !
아래 내용 class, function 으로 각각 만들어보기
1. + - 버튼 만들기
2. 등록버튼 누르면 list 나오게 만들기
<!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">
<title>REACT TIME</title>
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const App = () => {
const [input,setInput] = React.useState('')
const [list,setList] = React.useState([])
const handleChange=(e)=>{
setInput(e.target.value)
}
const handleSubmit = e =>{
e.preventDefault()
list.push(input)
setList(list)
setInput('')
}
return (
<>
<form onSubmit={handleSubmit}>
<input type="text" value={input} onChange={handleChange} />
<button type="submit">등록 </button>
</form>
<ul>
{
list.map((v,k)=>{
return <li key={k}>{v} </li>
})
}
</ul>
</>
)
}
ReactDOM.render(
<App />,
document.querySelector('#root')
)
</script>
</body>
</html>
3. reducer - 상태값을 객체로 관리하기 위해
원래는 Redux 라는 것이 최상위에서 상태값을 관리하는 것이었음! React에 들어오면서 -> useReducer 라는게 생김
Redux는 아~주 큰 프로젝트에서 힘을 발휘함
<!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">
<title>REACT TIME</title>
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const reducer = (state, action) => {
switch (action.type) {
case "change":
return {
...state,
input: action.payload.value
}
case "submit":
const {list} = {...state}
list.push(state.input)
return {
list,
input: '',
}
}
}
const App = () => {
// const [input,setInput] = React.useState('')
// const [list,setList] = React.useState([])
const initialState = {
input: '',
list: []
}
const [state, dispatch] = React.useReducer(reducer, initialState)
const handleChange = (e) => {
dispatch({ type: 'change', payload: { value: e.target.value } })
}
const handleSubmit = e => {
e.preventDefault()
dispatch({ type: 'submit', payload: {} })
}
return (
<>
<form onSubmit={handleSubmit}>
<input type="text" value={state.input} onChange={handleChange} />
<button type="submit">등록 </button>
</form>
<ul>
{
state.list.map((v, k) => {
return <li key={k}>{v} </li>
})
}
</ul>
</>
)
}
ReactDOM.render(
<App />,
document.querySelector('#root')
)
</script>
</body>
</html>
4. reducer 삭제
case "delete":
console.log(state.list)
let LIST = state.list.filter((v,k)=>{
console.log(v)
return k!=action.payload.num
})
return{
...state,
list:LIST,
}
=
case "delete":
return{
...state,
list:state.list.filter((v,k)=>{
return k!==action.payload.num
})
}
5. 수정
<!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">
<title>Document</title>
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const reducer = (state,action) => {
switch(action.type){
case "CHANGE":
return {
...state,
input:action.payload
}
case "SUBMIT":
const {list} = {...state}
list.push(state.input)
return {
...state, // input:'', list:['asdfasdf'] , visible
input:'',
list:list
}
case "DELETE":
return {
...state,
list: state.list.filter( (v,k) => {
return k !== action.payload
} )
}
case "VISIBLE":
return {
...state,
visible:action.payload
}
case "VISIBLEENTER":
const newlist = [...state.list]
newlist[action.payload.key] = action.payload.content
return {
...state,
list:newlist,
visible:Infinity
}
}
}
const App = () => {
const initalState = {
input:'',
list:[],
visible:Infinity,
}
const [state,dispatch] = React.useReducer(reducer,initalState)
const [content,setContent] = React.useState('')
const handleChange = e => { // evnet dispatch
const {value} = {...e.target}
dispatch({type:'CHANGE',payload:value})
}
const handleSubmit = e => { // dispatch
e.preventDefault()
dispatch({type:'SUBMIT'})
}
const handleClick = (index) => {
dispatch({type:'DELETE',payload:index})
}
const visibleContent = (index) => {
dispatch({type:'VISIBLE',payload:index})
setContent(state.list[index])
}
const visibleChange = e => {
console.log(e.target.value)
const {value} = {...e.target}
setContent(value)
}
const visibleEnter = e => {
const {key} = {...e.target.dataset}
if(e.key === 'Enter'){
dispatch({
type:'VISIBLEENTER',payload: {
key:key,
content:content
}
})
}
}
return (
<>
<form onSubmit={handleSubmit}>
<input type="text" onChange={handleChange} value={state.input} />
<button type="submit">등록</button>
</form>
<ul>
{
/*
login 한번클리하면 logout
logout 또 클릭하면 login
boolean -> 조건부 랜더링
*/
state.list.map((v,k)=>{
return (
<li key={k}>
<span onClick={()=>visibleContent(k)}>
{
state.visible === k
? <input
type="text"
value={content}
onKeyDown={visibleEnter}
onChange={visibleChange}
data-key={k}
/>
: v
}
</span>
<button onClick={()=>handleClick(k)}>X</button>
</li>
)
})
}
</ul>
</>
)
}
ReactDOM.render(
<App />,
document.querySelector('#root')
)
</script>
</body>
</html>
리액트 CRUD 공부 !
반응형
'블록체인 기반 핀테크 및 응용 SW개발자 양성과정 일기' 카테고리의 다른 글
[94일차]20210723 front server 연결 / Next 설치 (0) | 2021.07.23 |
---|---|
[ 93일차 복습 ] 리액트 React CRUD (0) | 2021.07.22 |
[92일차 복습] front + back React Webpack aws server로 가져오기 (0) | 2021.07.21 |
[92일차]20210721 aws-back-server & local-back-server 연결 (0) | 2021.07.21 |
[Front server] NginX 란? Amazon Aws NginX 설치 및 기본 환경설정 세팅하기 (0) | 2021.07.21 |