inflearn logo
강의

Course

Instructor

Creating a Super Simple REST API Bulletin Board with Spring Boot and React

Post Details Page

[해결됨]부분적으로 화면 이동이 안되는 부분이 있습니다.

4

Jang Jaehoon

26 asked

0

안녕하세요. 거의 다 완성했는데, 이상하게 화면 이동이 안되는 부분이 있어서 질문 올립니다.

화면 이동이 안되는 부분은

상세화면 PostDetail.js 에서 편집화면 PostEdit.js로 넘어가는 부분입니다.

먼저 PostDetail.js 소스입니다.

import React from 'react';
import {useNavigate, useParams} from "react-router-dom";
import {Link} from "react-router-dom";
import "./css/detail.css";
import {useEffect, useState} from "react";
import axios from "axios";

let PostDetail = () => {
    const {id} = useParams(); // URL에 포함된 파라미터 값을 가져오는 hook
    // http://localhost:3000/users/1 : このURLへ移動後、idが1 の場合に含まれるデータを持って来る。
    let navigate = useNavigate();

    let [post, setPost]
        = useState({ // useState:状態管理hook. 引数が状態
        title:"",
        content:""
    });

    const getPost = () =>{
        // axios : 非同期Api 呼出し 処理 library
        axios.get(`${process.env.REACT_APP_API_URL}/posts/${id}`)
            // REACT_APP_API_URL=http://localhost:8080/api
            .then(res=>
            {
                // console.log('情報の呼出し成功',res.data);
                console.log(res.data);
                setPost(res.data);
            }).catch(err=>{
                // console.error('情報の呼出し失敗',err);
                console.error(err);

            // axios.get() -> サーバーへの要請
            // -> 応答成功の場合 -> then() 実行
            // -> 応答失敗の場合 -> catch() 実行
        });  // The end of catch
    } // The end of getPost function

    // getPost Arrow 関数を実行。
    useEffect(()=>{
        getPost();
    },[]);

    const handleDelete = () => {
        if(!window.confirm("本当に削除しますか?")){
            return;
        }

        axios.delete(`${process.env.REACT_APP_API_URL}/posts/${id}`)
            .then(res=>{
                console.log(res.data);
                alert("削除されました。");
                navigate("/home");
            }).catch(
            err=>{
                console.log(err);
                alert("削除過程の中でエラーが発生致しました。");
            }
        ); // The end of catch

        // alert(`情報が削除されました。`);
    }

    // const post = {
    //     id,
    //     title: `The name of ${id}`,
    //     content: `The project of ${id}`,
    //     // empID: `EmployId of ${id}`,
    //     // info: `The other information of ${id}`
    // };



    return (
        <div className={"post-detail-container"}>
            <h1 className={"post-detail-title"}>{post.title}</h1>
            <p className={"post-detail-content"}>{post.content}</p>
            {/*<p className={"post-detail-empID"}>{post.empID}</p>*/}
            {/*<p className={"post-detail-info"}>{post.info}</p>*/}
            <div className={"button-group"}>
                <Link to={`/posts/edit/${post.id}`} className={"edit-button"}>
                    編集
                </Link>
                <button onClick={handleDelete} className={"delete-button"}>
                    削除
                </button>
            </div>
            <Link to="/home" className="back-link">戻る</Link>
        </div>
    );
}

export default PostDetail;

mysql rest-api spring-boot jpa react.js

Answer 6

0

Jang Jaehoon

해결되었습니다.

<Link to={/post/edit/${post.id}} className={"edit-button"}>

로 수정해야 하더군요.

0

Jang Jaehoon

참고로 다른 화면간 이동은 다 되는데, 이 상세화면과 수정 화면.. 두 화면 사이가 제대로 이동이 안되네요.

0

Jang Jaehoon

PostDetail.js에서 수정화면으로 넘어가는 버튼에서

값을 수정해봐도 잘 안들어가지네요.

<Link to={/posts/edit/${post.id}} className={"edit-button"}>

編集

</Link>

혹은

<Link to={/posts/edit/${id}} className={"edit-button"}>

編集

</Link>

이 두 가지 방법 모두 화면 이동이 안되는 상황입니다.

0

Jang Jaehoon

import {Link, useParams, useNavigate} from "react-router-dom";

import {useEffect, useState} from "react";

import "./css/edit.css";

import axios from "axios";

let PostEdit = () =>{

const{id} = useParams();

// useParam : React RouterからURLパスのparameterを持って来る。

const navigate = useNavigate(); // Page이동에 사용함.

let[title, setTitle] = useState("");

let[content, setContent] = useState("");

// let[post,setPost]=useState({

// title:"",

// content:""

// })

let [post, setPost]

= useState({ // useState:状態管理hook. 引数が状態

title:"",

content:""

});

useEffect(()=>{

// setTitle(${id}'s name );

// setContent(${id}'s project );

// 最初はバックエンド側のApi側から値を呼び出す。

axios.get(${process.env.REACT_APP_API_URL}/posts/${id})

// REACT_APP_API_URL=http://localhost:8080/api

.then(res=>

{

console.log('情報の呼出し成功',res.data);

setPost(res.data);

}).catch(err=>{

console.error('情報の呼出し失敗',err);

// axios.get() -> サーバーへのapi要請

// -> 応答成功の場合 -> then() 実行

// -> 応答失敗の場合 -> catch() 実行

} // The end of catch

); // The end of axios.get()

},[id]);

const handleOnChange = (e)=>{ 

// 変化を反映するロジック

const {name, value} = e.target;

setPost({

...post,

[name]: value

}

)

}

const handleSubmit = (e) => {

e.preventDefault();

axios.put(${process.env.REACT_APP_API_URL}/posts/${id}, post)

.then(res=>{

console.log(res.data);

alert("編集が完了されました。");

navigate(/posts/${id});

}).catch(

err=>{

console.log(err);

alert("編集を失敗致しました。");

}

)

alert("データが修正されました。");

// navigate("/post/edit/"+id);

navigate(/post/${id});

}

return (

<div className={"post-edit-container"}>

<h1 className={"post-edit-title"}>Edit Posting</h1>

<form onSubmit={handleSubmit} className={"post-edit-form"}>

<div className={"form-group"}>

<label htmlFor={"title"}>Name</label>

<input id={"title"} type={"text"} value={post.title}

// onChange={(e) => setTitle(e.target.value)}

onChange={handleOnChange} // 変化を反映するロジック

placeholder={"名前を入力してください。"} />

</div>

<div className={"form-group"}>

<label htmlFor={"content"}>Project</label>

<textarea id={"content"}  value={post.content}

// onChange={(e) =>

// setContent(e.target.value)}

onChange={handleOnChange} // 変化を反映するロジック

placeholder={"参加中のプロジェクトを入力してください。"}/>

</div>

{/*<div className={"form-group"}>*/}

{/* <label htmlFor={"empID"}>Project</label>*/}

{/* <textarea id={"empID"} value={empID} onChange={(e) => setContent(e.target.value)}*/}

{/* placeholder={"Enter Employee ID"}/>*/}

{/*</div>*/}

{/*<div className={"form-group"}>*/}

{/* <label htmlFor={"info"}>Project</label>*/}

{/* <textarea id={"info"} value={info} onChange={(e) => setContent(e.target.value)}*/}

{/* placeholder={"Enter Other Information"}/>*/}

{/*</div>*/}

<div className={"button-group"}>

<button type={"submit"} className={"submit-button"} >

編集

</button>

<Link to={/post/${id} } className={"cancel-button"}>

キャンセル

</Link>

</div>

</form>

</div>

);

}

export default PostEdit;

0

Jang Jaehoon

그 다음은 PostEdit.js입니다.


import {Link, useParams, useNavigate} from "react-router-dom";
import {useEffect, useState} from "react";
import "./css/edit.css";
import axios from "axios";

let PostEdit = () =>{
    const{id} = useParams();
    // useParam : React RouterからURLパスのparameterを持って来る。
    const navigate = useNavigate(); // Page이동에 사용함.

    let[title, setTitle] = useState("");
    let[content, setContent] = useState("");
    // let[post,setPost]=useState({
    //     title:"",
    //     content:""
    // })

    let [post, setPost]
        = useState({ // useState:状態管理hook. 引数が状態
        title:"",
        content:""
    });

    useEffect(()=>{
        // setTitle(`${id}'s name ` );
        // setContent(`${id}'s project ` );

        // 最初はバックエンド側のApi側から値を呼び出す。
        axios.get(`${process.env.REACT_APP_API_URL}/posts/${id}`)
            // REACT_APP_API_URL=http://localhost:8080/api
            .then(res=>
            {
                console.log('情報の呼出し成功',res.data);
                setPost(res.data);
            }).catch(err=>{
                console.error('情報の呼出し失敗',err);
                // axios.get() -> サーバーへのapi要請
                // -> 応答成功の場合 -> then() 実行
                // -> 応答失敗の場合 -> catch() 実行
            } // The end of catch
        ); // The end of axios.get()
    },[id]);

    const handleOnChange = (e)=>{ 
        // 変化を反映するロジック
        const {name, value} = e.target;
        setPost({
            ...post,
            [name]: value
            }
        )
    }

    const handleSubmit = (e) => {
        e.preventDefault();

        axios.put(`${process.env.REACT_APP_API_URL}/posts/${id}`, post)
            .then(res=>{
                console.log(res.data);
                alert("編集が完了されました。");
                navigate(`/posts/${id}`);
            }).catch(
                err=>{
                    console.log(err);
                    alert("編集を失敗致しました。");
                }
        )

        alert("データが修正されました。");
        // navigate("/post/edit/"+id);
        navigate(`/post/${id}`);
    }

    return (
         <div className={"post-edit-container"}>
             <h1 className={"post-edit-title"}>Edit Posting</h1>
             <form onSubmit={handleSubmit} className={"post-edit-form"}>
                 <div className={"form-group"}>
                    <label htmlFor={"title"}>Name</label>
                     <input id={"title"} type={"text"} value={post.title}
                         //    onChange={(e) => setTitle(e.target.value)}
                            onChange={handleOnChange} // 変化を反映するロジック
                    placeholder={"名前を入力してください。"}  />
                 </div>
                 <div className={"form-group"}>
                     <label htmlFor={"content"}>Project</label>
                     <textarea id={"content"}  value={post.content}
                               // onChange={(e) =>
                               //     setContent(e.target.value)}
                               onChange={handleOnChange} // 変化を反映するロジック
                               placeholder={"参加中のプロジェクトを入力してください。"}/>
                 </div>

                 {/*<div className={"form-group"}>*/}
                 {/*    <label htmlFor={"empID"}>Project</label>*/}
                 {/*    <textarea id={"empID"} value={empID} onChange={(e) => setContent(e.target.value)}*/}
                 {/*              placeholder={"Enter Employee ID"}/>*/}
                 {/*</div>*/}

                 {/*<div className={"form-group"}>*/}
                 {/*    <label htmlFor={"info"}>Project</label>*/}
                 {/*    <textarea id={"info"} value={info} onChange={(e) => setContent(e.target.value)}*/}
                 {/*              placeholder={"Enter Other Information"}/>*/}
                 {/*</div>*/}

                 <div className={"button-group"}>
                     <button type={"submit"} className={"submit-button"} >
                         編集
                     </button>

                     <Link to={`/post/${id}` } className={"cancel-button"}>
                         キャンセル
                     </Link>
                 </div>

             </form>
        </div>
    );
}

export default PostEdit; 

0

Jang Jaehoon

import React from 'react';

import {useNavigate, useParams} from "react-router-dom";

import {Link} from "react-router-dom";

import "./css/detail.css";

import {useEffect, useState} from "react";

import axios from "axios";

let PostDetail = () => {

const {id} = useParams(); // URL에 포함된 파라미터 값을 가져오는 hook

// http://localhost:3000/users/1 : このURLへ移動後、idが1 の場合に含まれるデータを持って来る。

let navigate = useNavigate();

let [post, setPost]

= useState({ // useState:状態管理hook. 引数が状態

title:"",

content:""

});

const getPost = () =>{

// axios : 非同期Api 呼出し 処理 library

axios.get(${process.env.REACT_APP_API_URL}/posts/${id})

// REACT_APP_API_URL=http://localhost:8080/api

.then(res=>

{

// console.log('情報の呼出し成功',res.data);

console.log(res.data);

setPost(res.data);

}).catch(err=>{

// console.error('情報の呼出し失敗',err);

console.error(err);

// axios.get() -> サーバーへの要請

// -> 応答成功の場合 -> then() 実行

// -> 応答失敗の場合 -> catch() 実行

});  // The end of catch

} // The end of getPost function

// getPost Arrow 関数を実行。

useEffect(()=>{

getPost();

},[]);

const handleDelete = () => {

if(!window.confirm("本当に削除しますか?")){

return;

}

axios.delete(${process.env.REACT_APP_API_URL}/posts/${id})

.then(res=>{

console.log(res.data);

alert("削除されました。");

navigate("/home");

}).catch(

err=>{

console.log(err);

alert("削除過程の中でエラーが発生致しました。");

}

); // The end of catch

// alert(情報が削除されました。);

}

// const post = {

// id,

// title: The name of ${id},

// content: The project of ${id},

// // empID: EmployId of ${id},

// // info: The other information of ${id}

// };

return (

<div className={"post-detail-container"}>

<h1 className={"post-detail-title"}>{post.title}</h1>

<p className={"post-detail-content"}>{post.content}</p>

{/*<p className={"post-detail-empID"}>{post.empID}</p>*/}

{/*<p className={"post-detail-info"}>{post.info}</p>*/}

<div className={"button-group"}>

<Link to={/posts/edit/${post.id}} className={"edit-button"}>

編集

</Link>

<button onClick={handleDelete} className={"delete-button"}>

削除

</button>

</div>

<Link to="/home" className="back-link">戻る</Link>

</div>

);

}

export default PostDetail;

마지막 강의 내용 수정 화면이 기능을 못하네요.

0

2

0

68강 문제 풀이

0

11

1

현대 쿼리 복잡성에 관한 질문

0

16

2

스프링부트 서버 에러나요

0

120

1

지금 이게 맞는건지 문의드립니다.

0

90

1

7.React UI구현하기 에서 css파일을 어디서 다운받나요?

0

102

2

spring 과 mysql 연결이 안돼요

0

165

1

Css 복사하는 코드 첨부되어 있나요?

0

115

2

스프링부트 에러

0

184

2

자바 17

0

110

2

리액트 부분 vscode 써도 괜찮을까요

0

176

1

선생님 덧글의 답글

0

163

2

(재업) 선생님 제발 도와주세요

0

161

1

앞에 내용 다 따라했는데 실행이안됩니다 자꾸

0

121

1

실행시 에러

0

107

1

최초에 서버 키는게 안됩니다 ㅠㅠ

0

131

1

[게시글 목록 페이지]수업에서 강의 내용대로 진행이 안되네요.

0

145

2

두번째 게시글 등록이 안되네요.

0

253

4

스프링 기동 하는 부분에서 계속 에러가 나와서 질문 드립니다.

0

233

4

리액트 사용시 컴포넌트 선언과 변수 선언 관련 질문

0

143

2

DB에 데이터가 저장이 되지 않습니다.

0

201

2

Spring Boot , Java 설치시 버전

0

310

3

SpringBoot 초기세팅 수강중 오류가 있어 문의드립니다.

0

265

2

중괄호 Tab to Exit 설정

0

197

1