reactjs 从数据库获取图片并在react中显示

hgqdbh6s  于 2023-04-05  发布在  React
关注(0)|答案(1)|浏览(146)

我试图检索图像,然后在页面上显示它,但不知何故,它不显示图像。相反,它抛出此错误:Failed to load resource: the server responded with a status of 400 (). Uncaught (in promise) StorageApiError: The resource was not found
我的图像路径作为徽标列存储在Projects表中,并且相同的字符串也存储在存储桶中。我不明白这个问题

const Dashboard = () => {
  const [projects, setProjects] = useState<Project[]>([])

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

  const getProjects = async () => {
    try {
      const {data: projects, error} = await supabase.from('Projects').select('*')
      if (error) {
        throw error
      }
      setProjects(projects as Project[])
    } catch (error) {}
  }

  const getSignedUrl = async (filename: string) => {
    const {data, error} = await supabase.storage.from('project-logo').createSignedUrl(filename, 60)
    if (error) {
      throw error
    }
    return data.signedUrl
  }

  return (
    <div className='row'>
      {projects.map((project) => (
        <div className='col-lg-4 mb-5' key={project.id}>
          <div className='card card-custom card-stretch-50 shadow'>
            <div className='card-header d-flex align-items-center'>
              <a href={`/project/${project.id}/detail`}>
                <h3 className='card-title'>{project.name}</h3>
              </a>
              <img src={`${getSignedUrl(project.logo)}`} alt={project.name} />
            </div>
            <div className='card-body'>{project.description}</div>
          </div>
        </div>
      ))}
    </div>
  )
}
x6yk4ghg

x6yk4ghg1#

你的代码有两个问题:
1.管理;
2. http请求(最致命的)。您在map语句中请求数据(循环请求),导致400错误。
对于1:

const Dashboard = () => {
  const [projects, setProjects] = useState<Project[]>([])

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

  const getProjects = async () => {
    try {
      const {data: projects, error} = await supabase.from('Projects').select('*')
      if (error) {
        throw error
      }
      setProjects(projects as Project[])
    } catch (error) {}
  }

  return (
    <div className='row'>
      {projects.map((project) => (
        <div className='col-lg-4 mb-5' key={project.id}>
          <div className='card card-custom card-stretch-50 shadow'>
            <div className='card-header d-flex align-items-center'>
              <a href={`/project/${project.id}/detail`}>
                <h3 className='card-title'>{project.name}</h3>
              </a>
              <img src={`${project.logoUrl}`} alt={project.name} />
            </div>
            <div className='card-body'>{project.description}</div>
          </div>
        </div>
      ))}
    </div>
  )
}

对于2.在服务器端将logoUrl属性添加到项目响应中。

相关问题