简体   繁体   English

React给我TypeError:尝试通过帖子数组映射时props.posts.map不是函数

[英]React gives me TypeError: props.posts.map is not a function when trying to map through an array of posts

I've been trying to write some simple React code to fetch data from a mock API and display it on a page. 我一直在尝试编写一些简单的React代码,以从模拟API提取数据并将其显示在页面上。 But when trying to map through my array of posts returned by axios from an async function it gives me an error. 但是,当尝试映射axios从异步函数返回的帖子数组时,它给了我一个错误。

I've tried setting props.posts to a variable and it still doesn't work. 我尝试将props.posts设置为变量,但仍然无法正常工作。

Here's my app structure and the function I use to get the users from the API as JSON: 这是我的应用程序结构以及用于以JSON形式从API获取用户的函数:

function App() {
    // Hook that declares a posts state
    const [posts, setPosts] = useState([])

    useEffect(() => {
        getPosts().then(setPosts)
    }, [])
    return (
        <div className='App'>
            <header className='App-header'>
                <PostList posts={posts} />
            </header>
        </div>
    )
}

function PostList(props) {
    return (
        <ul>
            {props.posts.map(post => (
                <Post post={post} />
            ))}
        </ul>
    )
}

function Post(props) {
    return <li>{props.post.title}</li>
}

async function getPosts() {
    try {
        let posts = await axios.get(
            'https://jsonplaceholder.typicode.com/posts'
        )
        console.log(posts)
        return posts
    } catch (error) {
        console.error(error)
    }
}

And this is the problematic bit: 这是有问题的位:

function PostList(props) {
    return (
        <ul>
            {props.posts.map(post => (
                <Post post={post} />
            ))}
        </ul>
    )
}

I expect the application to map through the array of posts but it gives me an error every time. 我希望该应用程序能够映射整个帖子数组,但是每次都会给我一个错误。

The most likely scenario is that your axios request is failing for some reason. 最可能的情况是您的axios请求由于某种原因而失败。 Maybe there's an error, or a CORS problem, and posts isn't an array when you go to set it. 也许有错误或CORS问题,并且在您进行设置时posts不是数组。 You should have some validation either in your useEffect or in getPosts() like: 您应该在useEffectgetPosts()进行一些验证,例如:

async function getPosts() {
    try {
        let posts = await axios.get(
            'https://jsonplaceholder.typicode.com/posts'
        )
        if (!Array.isArray(posts)) {
          console.log("posts isn't an array: ", posts);
          return [];
        }
        return posts;
    } catch (error) {
        console.error('An error occurred: ', error);
        return [];
    }
}

Just make sure, even if there's an error, you're always returning an array. 只要确保即使有错误,也总是返回一个数组。

Try adding a ternary for the posts attribute in case post is not an array: 如果post不是数组,请尝试为posts属性添加三元组:

return (
    <div className='App'>
        <header className='App-header'>
            <PostList posts={posts && posts.length > 0 ? posts : []} />
        </header>
    </div>
)

Axios return an object with info about the request (status, headers, data, etc) I think you need to find request.data. Axios返回一个对象,其中包含有关请求的信息(状态,标头,数据等),我认为您需要找到request.data。 The error is because you are trying to map over an object instead of an array. 该错误是因为您试图映射到对象而不是数组。

 async function getPosts() {
    try {
        let posts = await axios.get(
            'https://jsonplaceholder.typicode.com/posts'
        )
        return posts.data 
               ˆˆˆˆˆˆˆˆˆˆ
    } catch (error) {
       ...
    }
}

docs: https://github.com/axios/axios docs: https : //github.com/axios/axios

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 反应:this.props.posts.map不是一个函数 - React: this.props.posts.map is not a function 类型错误:将状态设置为数组时,this.state.posts.map 不是函数 - TypeError: this.state.posts.map is not a function when setting state to a array REACTJS:类型错误:posts.map 不是 function - REACTJS: TypeError: posts.map is not a function React,Array obj上的TypeError(this.props.data.map不是函数) - React, TypeError (this.props.data.map is not a function) on an Array obj 反应:TypeError:this.props.courses.map不是一个函数 - React: TypeError: this.props.courses.map is not a function TypeError:尝试读取通过props传递的数组时,无法读取未定义的属性“ map” - TypeError: Cannot read property 'map' of undefined, while trying to .map() an array passed through props 反应-TypeError:this.props.courses.map不是函数 - React - TypeError: this.props.courses.map is not a function 未处理的运行时错误类型错误:posts.map 不是 function - Unhandled Runtime Error TypeError: posts.map is not a function 为什么我有这个错误“Uncaught TypeError: posts.map is not a function” - Why I have this error "Uncaught TypeError: posts.map is not a function" “Uncaught TypeError: posts.map is not a function”,如何解决这个错误? - "Uncaught TypeError: posts.map is not a function" , How to solve this error?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM