【问题标题】:React.JS: Why is useState() empty at the beginning?React.JS:为什么 useState() 一开始是空的?
【发布时间】:2022-08-11 02:08:29
【问题描述】:

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

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

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

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

    标签: javascript reactjs typescript


    【解决方案1】:

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

    <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 包含一个值时,这才会有条件地将&lt;img&gt; 元素包含在标记中。

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 1970-01-01
      • 2021-10-03
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      相关资源
      最近更新 更多