next.jsでフロントwebappの開発をしています。
get APIのレスポンスの値を使って、画面を表示したいのですがうまくいきません。ご教授いただきたいです。
以下試したことです。
・レスポンスをconsolo.log(JSON.stringify(posts))で出力してみたところ、APIのレスポンスは取得できていました。以下の形でした。
{"Post":[{"id":"61e、、、、、},{"id":"61e、、、、、},{"id":"61e、、、、、},]}
・JSONを配列の形にして、mapで要素の表示をしたかったので、
JSONからの治し方がおかしいのかと思い、以下色々チャレンジしてみましたが、どれもうまくいきませんでした。
const json =JSON.stringify(props.result)
const json =JSON.parse(props.result)
const json =JSON.parse(JSON.stringify(props.result))
const json = Object.entries(JSON.parse(JSON.stringify(props.result)))
const json =Object.entries(JSON.stringify(props.result))
const json = Object.value(JSON.parse(JSON.stringify(props.result)))
const json =Object.value(JSON.stringify(props.result))
const json = [JSON.parse(JSON.stringify(props.result))]
const json = [JSON.stringify(props.result)]
ソースコード
export default function Home({ allPostsData, post }) { const result = getPosts() return ( <Layout home> <Head> <title>{siteTitle}</title> </Head> <section className={utilStyles.headingMd}> </section> <section className={`${utilStyles.headingMd} ${utilStyles.padding1px}`}> <ul className={utilStyles.list}> <Post result={result}> </Post> </ul> </section> </Layout> ) } async function getPosts() { const url = "http://localhost:8000/api/post?count=5&lastPostId=null"; const params = { method: "GET" }; const response = await fetch(url, params); const posts = await response.json() return posts }
export default function Post(props) { const json = Object.entries(JSON.parse(JSON.stringify(props.result))) //jsonに入る値を色々試してみた。 console.log("Post側の確認1" + props.result) console.log("Post側の確認1" + json) console.log("Post側の確認2" + JSON.parse(JSON.stringify(props.result))) console.log("Post側の確認3" + Object.entries(JSON.stringify(props.result))) console.log("Post側の確認4" + [JSON.parse(JSON.stringify(props.result))]) console.log("Post側の確認5" + JSON.stringify(props.result)) console.log("Post側の確認6" + JSON.parse(props.result)) return ( <li> {json.map(post => ( <Card style={{ width: '40rem' }}> {/* {if(class=){ }} */} <Link href="./userPosts"> rio </Link> <Card.Img variant="top" src={post.imageUrl} /> <Card.Body> <Card.Text> ❤️{post.favosCount} 件 コメント{post.commentsCount} 件 </Card.Text> <Card.Title>{post.title} </Card.Title> </Card.Body> </Card> ))} </li> ) }
よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/05/06 12:33