首页 > 解决方案 > 为什么我不能映射这个数组

问题描述

你能帮我弄清楚为什么我不能映射这个数组。下面是错误和我正在运行的代码:

TypeError: posts.map is not a function

这是我的代码导致上述错误:

import React from 'react';
import {useEffect, useState} from 'react';
import { Container, Row, Col } from 'bootstrap-4-react';

export default function Post() {
     //posts array to be mapped
    const [posts, setPosts] = useState([{ 
        title: "",
        postContent: ""
    }]);

    useEffect(() => {
    //fetches a GET route
        fetch(`${process.env.REACT_APP_SERVER_URL}/posts/:id`).then(res => {    
            if (res.ok) {
                return res.json()
            }
        }).then(jsonRes => setPosts(jsonRes));
    })

    return (
    <div>
        <h1>Hello</h1>
        //cant seem to be able to map this array
        {posts.map(post => {  
            <>
            <h1>{post.title}</h1>
            <p>{post.postContent}</p>
            </>
        })}
    </div>
    )}

标签: javascriptreactjs

解决方案


You need to wrap the mapped returned code block within parenthesis () and not in curly brackets {} in order to return the html correctly

//...


  return (
    <div>
      <h1>Hello</h1>
        {posts.map(post => (  
          <>
            <h1>{post.title}</h1>
            <p>{post.postContent}</p>
          </>
        ))}
    </div>
  )
}


Edit: Also, I suggest adding an empty dependency array as the second argument for your useEffect(() => { //your code }, []) This will make it so your component doesn't re-render sporadically and end up fetching your data a ridiculous amount of times.


推荐阅读