繁体   English   中英

React.JS:为什么 useState() 一开始是空的?

[英]React.JS: Why is useState() empty at the beginning?

我尝试发出GET请求,并且到目前为止有效。 但是,页面上总是可以显示不同的图像,这就是为什么在请求之后直接存储一个 ID,然后可以使用它通过 URL 捕获图像。

但是,一开始useState({})"post"中没有任何内容,因此它是空的。

因此会生成这样的错误消息:

GET https://myip.net/undefined/undefined-normal.jpg 404 (Not Found)

post.postId一开始是未定义的,因为里面还没有任何东西。 在那之后,1ms 之后,它不再是未定义的,并且显示了图像。

但这很烦人,因为一开始没有找到图像并且控制台中出现错误消息。

我希望有一个人可以帮助我:)

import React from 'react'
import { Link, useLocation, Navigate } from 'react-router-dom'
import axios from "axios"
import { useState, useEffect } from 'react'

const Art = () => {

    const [post, setPost] = useState({})

    function useQuery() {
        const { search } = useLocation();
        return React.useMemo(() => new URLSearchParams(search), [search]);
    }

    let query = useQuery();

    useEffect(() => {
        const token = localStorage.getItem("token")
        axios.get("myip.com").then(function (res) {

            console.log("debug")

            return setPost(res.data.cnt)
        })
    }, [])

    if (query.get("id")) {
        if (post.code == "403") {
            console.log("403")
            return (
                <div><p className='text-white'>not found</p></div>
            )
        } else {

            console.log(post)

            return (
                <div>
                    <div className='container mx-7 py-9'>
                        <img className='h-96 rounded-drawlie' src={"myip.com/" + post.postId + "/" + post.postId + "-normal.jpg"}></img>

                        <p className='text-white'>{post.description}</p>
                    </div>
                </div>
            )
        }
    }

    return (
        <Navigate to="/" />
    )

}

export default Art

在 state 值可用之前,不要显示图像。 例如:

<div className='container mx-7 py-9'>
  { post.postId ?
    <img className='h-96 rounded-drawlie' src={"myip.com/" + post.postId + "/" + post.postId + "-normal.jpg"}/> :
    null
  }
  <p className='text-white'>{post.description}</p>
</div>

仅当post.postId包含值时,这将有条件地在标记中包含<img>元素。

或者,您可以将 state 初始化为一些有意义的默认图像的postId值:

const [post, setPost] = useState({ postId: 1 });

基本上,对于初始渲染,您要么显示已知图像,要么不显示图像。

最初,您的帖子是空的 object 然后您通过http请求填充帖子,该请求本质上是async的,因此您得到undefined

您可以在此处使用条件渲染,例如

{post.postId &&
        <div className='container mx-7 py-9'>
                    <img className='h-96 rounded-drawlie' src={"myip.com/" + post.postId + "/" + c + "-normal.jpg"}></img>

                    <p className='text-white'>{post.description}</p>
                </div>
      }
<img className='h-96 rounded-drawlie' src={post.postId ? "myip.com/" + post.postId + "/" + post.postId + "-normal.jpg" : "default.jpg"}></img>

您可以默认使用占位符图像,例如加载 gif

暂无
暂无

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

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