nextjs 将数据传递给组件

nextjs passing data to component

我这辈子都想不出将从 API 获取的数据传递给 canvas 组件。在我看来,handleSubmit() 函数中可用的数据超出了 canvas 道具的范围。我感谢任何帮助。谢谢

我有一个日期选择器,它将选定的值作为参数传递给 API。数据获取得很好。我可以 console.log 但我似乎找不到将数据发送到我的 canvas 组件的方法。

import React, { useState, useEffect } from 'react'
import Layout from '../components/layout'
import Sidebar from '../components/sidebar'
import DatePicker from 'react-datepicker'
import Canvas from '../components/canvas'

import 'react-datepicker/dist/react-datepicker.css'

export default function Ground({ track }) {
  function epoch(date) {
    date = Date.parse(date)
    date = date / 1000
    return date
  }

  const [startDate, setStartDate] = useState(new Date())
  const rightThisSecond = Math.round(Date.now() / 1000)
  const beginDate = Math.round(Date.now(startDate) / 1000)

  const handleSubmit = async (e) => {
    e.preventDefault()
    // console.log(epoch(startDate))

    const beginDate = epoch(startDate)
    // console.log(beginDate)
    // ... submit to API or something
    const res = await fetch(
      `/api/tracks/timeseries/${beginDate}/${rightThisSecond}`
    )
    const track = await res.json()
    // console.log(track)
  }
  return (
    <section>
      <h2>Layout Example (Ground)</h2>
      <form onSubmit={handleSubmit}>
        <DatePicker
          selected={startDate}
          onChange={(date) => setStartDate(date)}
        />
        <button type='submit'>Submit</button>
      </form>

      <section>
        <>
          <Canvas data={track} /> // doesn't seem to reach here.
        </>
      </section>
    </section>
  )
}

Ground.getLayout = function getLayout(page) {
  return (
    <Layout>
      <Sidebar />
      {page}
    </Layout>
  )
}

你的 handleSubmitasync 所以 const track = await res.json() 会很好地执行,在组件已经渲染并且永远不会被使用之后。

您需要在数据 returns 之后更新状态,以便组件可以使用 setTrack(track) 之类的方法重新呈现获取的数据。然后在您的组件中,您可以传递来自状态的数据。

示例:

const [track, setTrack] = useState()

...

setTrack(await res.json())

...

<Canvas data={track} />