三項演算子(ternary operator) を使った条件分岐の処理
{threads.length === 0 ? ( <p>投稿がまだありません</p> ) : ( ... )} threads.length === 0 → スレッドがない場合
<p>投稿がまだありません</p> を表示
: の後にある ( ... ) → スレッドがある場合
threads.map((thread) => {...}) を使ってスレッド一覧を表示する処理が入ります
つまり、この部分の : の後には スレッドがあるときの表示内容を書く 必要がある。今回のコードではul要素の中でthreads.map()を使ってリストを作成してる。
import { useEffect, useState } from "react";
import MoveCreateThreas from "../button/HomeBotton/CreateThreadsBotton";
const Home = () => {
const [threads, setThreads] = useState([]);
useEffect(() => {
fetch("http://localhost:8080/app/threads", { method: "GET" })
.then((res) => res.json())
.then((data) => {
console.log("Fetched Data:", data); // 取得データを確認
setThreads(data);
})
.catch(() => alert("エラー")); //この辺( .then((res) ,.then((data) )はGETの時のほぼ定型文
}, []);
return (
<div>
<h1>ここがホーム画面</h1>
<MoveCreateThreas />
{threads.length === 0 ? (
<p>投稿がまだありません</p>
) : (
<ul>
{/*情報をとってきて並べるときの書き方。 */}
{threads.map((thread) => {
console.log(thread);
return (
<li key={thread.id}>
<p>ID: {thread.id}</p>
<p>タイトル: {thread.title}</p>
<p>内容: {thread.content}</p>
<p>ユーザー: {thread.user.name}</p>
{/*userメソッドの中のnameを取るって意味になる。*/}
<p>投稿日: {thread.postedAt}</p>
</li>
);
})}
</ul>
)}
;
</div>
);
};
export default Home;