简体   繁体   English

nextjs 将数据传递给组件

[英]nextjs passing data to component

I can't figure out for the life of me to pass the data I fetched from my API to the canvas component.我一生都无法将我从 API 获取的数据传递给画布组件。 It seems to me where the data is available in the handleSubmit() function it is out of scope to the canvas prop.在我看来, handleSubmit()函数中可用的数据超出了画布道具的范围。 I appreciate any help.我很感激任何帮助。 Thanks.谢谢。

I have a datepicker that passes the selected value as a parameter to the API.我有一个日期选择器,它将所选值作为参数传递给 API。 The data is fetched just fine.数据被提取得很好。 I can console.log it but I can't seem to find a way to send the data to my canvas component.我可以使用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>
  )
}

Your handleSubmit is async so const track = await res.json() will execute just fine, after the component has already rendered and it'll never be used.您的handleSubmitasync因此const track = await res.json()将执行得很好,在组件已经呈现并且永远不会被使用之后。

You need to update the state after your data returns so that the component can rerender with the fetched data, using something like setTrack(track) .您需要在数据返回后更新状态,以便组件可以使用获取的数据重新渲染,使用类似setTrack(track) Then in your component you can pass the data from the state.然后在您的组件中,您可以从状态传递数据。

Example:例子:

const [track, setTrack] = useState()

...

setTrack(await res.json())

...

<Canvas data={track} />

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

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