简体   繁体   English

反应:无法将 useState 设置为对象数组。 控制台日志显示未定义

[英]REACT: Can't set useState to an array of objects. Console log shows undefined

I am using react and a mongoose/mongo database.我正在使用 react 和 mongoose/mongo 数据库。 On the page loading, I do an API call and receive an array of objects (they are "posts" with titles, descriptions, etc).在页面加载时,我调用 API 并接收一组对象(它们是带有标题、描述等的“帖子”)。 I am trying to map over the data to dynamically display the post info on separate cards.我正在尝试对数据进行 map 以在单独的卡上动态显示发布信息。 I can get the data from the API call, but when I try to change state to the array of objects and console log it, I get undefined.我可以从 API 调用中获取数据,但是当我尝试将 state 更改为对象数组并控制台记录它时,我得到了未定义。

Attached is the photo of the code and result:附上代码和结果的照片:

Console log of Info Info 的控制台日志

The code of API call (related to pic 1 - please notice the code line numbers) API调用的代码(与图1相关-请注意代码行号)

Why isn't usestate accepting the change in state from the data?为什么 usestate 不接受数据中 state 的变化? Attached is my code:附上我的代码:

import React, { useState, useEffect } from 'react'
import API from "../utils/API"


const Home = () => {

    const [PostObject, setPosts] = useState({
        title: "",
        description: "",
        image: ""
    })

    const [PostList, setList] = useState()


    useEffect(() => {
        retrievePosts()
    }, [])


    const handleInputChange = (e) => {
        e.preventDefault()
        setPosts({ ...PostObject, [e.target.name]: e.target.value })
    }


    const createPost = (e) => {
        e.preventDefault()
        setPosts({ ...PostObject, title: "", description: "", image: "" })
        API.addPost(PostObject)
            .then(retrievePosts())
    }


    const retrievePosts = () => {
        API.getPost()
            .then(res => {
                console.log(res.data);
                setList(res.data)
                console.log(PostList);
            })
    }

Why isn't usestate accepting the change in state from the data?为什么 usestate 不接受数据中 state 的变化? Attached is my code:附上我的代码:

Because you attached an empty dependency array to useEffect as in:因为您将一个空的依赖数组附加到useEffect ,如下所示:

useEffect(() => {
        retrievePosts()
    }, [])

If you pass an empty dependency array, this useEffect will be called only once.如果你传递一个空的依赖数组,这个 useEffect 只会被调用一次。 If you want to run the useEffect after every data change you have to pass the data to the dependency array:如果要在每次数据更改后运行useEffect ,则必须将数据传递给依赖数组:

useEffect(() => {
            retrievePosts()
        }, [data /*i.e PostList*/])

However, be careful not to re-render the component infinite amount of times.但是,请注意不要无限次地重新渲染组件。 You can check libraries like React-Query and SWR您可以检查React-QuerySWR等库

One more thing:还有一件事:

I can get the data from the API call, but when I try to change state to the array of objects and console log it, I get undefined.我可以从 API 调用中获取数据,但是当我尝试将 state 更改为对象数组并控制台记录它时,我得到了未定义。

setState is an async call. setState是一个异步调用。 You can't log the data right after calling setData .调用setData后,您无法立即记录数据。 Take a look at this article or to this question and see if they help看看这篇文章或这个问题,看看他们是否有帮助

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM