【问题标题】:NEXTJS: try to show simple data jsonNEXTJS:尝试显示简单数据 json
【发布时间】:2021-12-25 10:23:13
【问题描述】:

我尝试显示我的 JSON 的内容,数据没有更新,它只显示我的空数组(来自 dataContest)。我试图将函数和其他测试的返回值作为返回值,并查看了其他论坛,但没有任何帮助。

the JSON comes from my supabase, this is the content I want to display

我的代码:

import { useState, useEffect} from 'react'
import { supabase } from '../utils/supabaseClient'

export default function Auth() {
    const dataContest = useState([])


    useEffect(() => {
      loadData()
    })

  async function loadData() {
      try {
        let { data: contest, error } = await supabase
          .from('contest')
          .select(`
            title, startDate, endDate, description,
            cryptoMonnaie (
              name
            ),
            category (
              name
            )
          `)
  
        if (error) {
          throw error
        }
        console.log(contest)
        dataContest.pop()
        dataContest.pop()
        dataContest.push(contest)
        
     
      } catch (error) {
        alert(error.message)
      } finally {
      }
  }

  return (
    <div className="row flex flex-center">
      <div className="col-8 form-widget">
        <h1 className="header">Contest Page</h1>
        <div>
        <table>
            <tr>
              <td>Title</td>
              <td>StartDate</td>
              <td>EndDate</td>
              <td>Statut</td>
              <td>Category</td>
            </tr>
            {dataContest!=[] && dataContest.map((title, startDate, endDate, description, cryptoMonnaie, category) => (
                  <tr key={title}>
                    <td>{title}</td>
                    <td>{startDate}</td>
                    <td>{endDate}</td>
                    <td>{description}</td>
                    <td>{cryptoMonnaie}</td>
                    <td>{category}</td>
                  </tr>
                ))}
        </table>
        </div>
      </div>
    </div>
  )
}

结果: the result on the interface

【问题讨论】:

    标签: html json next.js


    【解决方案1】:

    您可能希望使用状态设置方法来存储数据。重新迭代你的代码,你可能会有类似的东西:

    const YourComponent =  () => {
        const [data, setData] = useState([])
        
        useEffect(() => {
          loadData()
        }, [])
    
        async function loadData() {
           const data = [/* your data fetched from the database */]
           
           setData(data)
        }
    
        return (/* your jsx */)
    }
    

    这是使用 useState 钩子的正确方法。你可能想看看这篇文章:https://reactjs.org/docs/hooks-state.html

    在将其放入舞台之前,请确保使用 JSON.parse(data_from_database)。

    【讨论】:

      猜你喜欢
      • 2018-05-25
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2020-07-03
      相关资源
      最近更新 更多