Next.js 使用 getServerSideProps 如何将道具从页面传递到组件? [英] Next.js using getServerSideProps how do i pass props from page to components?

查看:19
本文介绍了Next.js 使用 getServerSideProps 如何将道具从页面传递到组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取 coingecko-api 以访问比特币的实时价格.我正在尝试将 getServerSideProps 的返回道具传递给我的 <CalculatorBuy/> 组件,该组件是 <Main/> 组件的一部分.我试图在 calculatorbuy.js 中导入异步函数,但我得到了未定义的对象.如何将 index.js 中的 props 传递给 main.jscalculatorbuy.js 组件.在 index.js 中,一切都像魅力一样工作,但我想直接在组件中使用 props 值.

index.js导出默认函数 Home(props) {常量 {数据} = props.result;控制台.log(数据);返回 (<div className=容器"><头><title>购买比特币</title><link rel="图标";href="/favicon.ico";/><元名称=视口"content="width=device-width, initial-scale=1.0"></meta></头><标题/><主要/><页脚/><风格 jsx>{`.容器 {最小高度:100vh;显示:弯曲;弹性方向:列;证明内容:中心;对齐项目:居中;}`} </style></div>)}导出异步函数 getServerSideProps(context) {常量结果 = 等待 coinGeckoClient.simple.price({ids:比特币",vs_currencies:欧元",});返回 {道具: {结果,},}}

main.js导入反应,{ useState } from 'react';从'@material-ui/core/Button'导入按钮;从 './calculatorbuy.js' 导入 Calculatorbuy从 './calculatorsell.js' 导入 Calculatorsell导出默认函数 Main() {const [ showMe, setShowMe ] = useState(true);函数切换(){如果(!showMe){设置显示(真);}别的 {设置显示(真);}}功能切换2(){如果(showMe){设置显示(假);}别的 {设置显示(假);}}返回 (<主类名=主"><div className=盒子"><div className="按钮"><按钮 onClick={toggle} 变体=概述";颜色=主要"样式={{宽度:120,marginRight:10}}>库普</按钮><按钮 onClick={toggle2} 变体=概述";颜色=次要"样式={{宽度:120,marginRight:10}}>斯普泽达</按钮><按钮变体=概述"颜色=默认"样式={{宽度:120,}}>历史</按钮></div><div style={{ display: showMe?"block":"none";}}><计算器购买/></div><div style={{ display: !showMe?"block":"none"}}><计算器卖/></div></div><div className="room-for-socials></div>

import React, { useState } from 'react';从'@material-ui/core/TextField'导入TextField;从'@material-ui/core/Button'导入按钮;从'./livebsv.js'导入Livebsv;导出默认函数 Calculatorbuy() {常量 [值,setValue] = useState(0);返回 (<form className="计算器";noValidate autoComplete=关闭">

<Livebsv/></div><div className="typebox"><div className="文本字段"><TextField 错误={false} id="outlined-number";标签=PLN"helperText =最小.wartość 100zł"类型=电话";价值={价值}InputProps={{inputProps: { min: "100", max: "5000", step: "0.01";}}}变体=概述";onKeyPress={(e) =>{if (!/[0-9]/.test(e.key)) {e.preventDefault();}}}onChange={(e) =>setValue(e.currentTarget.value)}onKeyPress={(e) =>{if (!/[0-9]/.test(e.key)) {e.preventDefault();}}}onBlur={(e) =>{if (e.currentTarget.value > 0 & e.currentTarget.value < 100 )设置值(100);否则如果(e.currentTarget.value > 5000)设置值(5000);}}/></div><div className="文本字段"><TextField disabled id=outlined-disabled";value={(value).toFixed(8)} label=BSV"变体=概述";

解决方案

通过在 index.js(getServerSideProps) 上加载结果,你开始很好.

然后,要将数据传递给 Main,您必须将其添加为组件的属性:

<主数据={data}/>

现在,由于 Main 需要一个参数,它必须在 main.js 中定义:

导出默认函数 Main(props) {常量数据 = props.data;...}

然后,对于 Calculatorbuy 组件,您必须在 Main 上执行相同的操作.定义 props 并使用它.

I am trying to fetch coingecko-api to access live price of bitcoin. I am trying to pass return props of getServerSideProps to my <CalculatorBuy /> component which is the part of <Main /> component. I was trying to import async function in calculatorbuy.js but i'm getting undefined object. How to pass props from index.js to main.js and calculatorbuy.js components. In index.js everything work like a charm but i would like to use props value directly in components.

index.js

export default function Home(props) {

  const {data} = props.result;
  console.log(data);

  return (
    <div className="container">
      <Head>
        <title>Buy BTC</title>
        <link rel="icon" href="/favicon.ico" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0"></meta>
      </Head>
      <Header />

      <Main />

      <Footer />
      <style jsx> {`
        .container {
          min-height: 100vh;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
      `} </style>
    </div>
  )
}

export async function getServerSideProps(context) {
  const result = await coinGeckoClient.simple.price({
      ids: "bitcoin",
      vs_currencies: "eur",
  });
  return {
      props: {
          result,
      },
  }
  
}

main.js

import React, { useState } from 'react';
import Button from '@material-ui/core/Button';
import Calculatorbuy from './calculatorbuy.js'
import Calculatorsell from './calculatorsell.js'
  

export default function Main() {
    const [ showMe, setShowMe ] = useState(true);
    function toggle (){
        if  (!showMe) {
            setShowMe(true);
        }
        else {
            setShowMe(true);
        }
    }
    function toggle2 (){
        if  (showMe) {
            setShowMe(false);
        }
        else {
            setShowMe(false);
        }
    }
    
    return (
        <main className="main">
            <div className="box">
                <div className="buttons">

                    <Button onClick={toggle} variant="outlined" color="primary" style={{width: 120, marginRight: 10}}>
                        KUP
                    </Button>
                    <Button onClick={toggle2} variant="outlined" color="secondary" style={{width: 120, marginRight: 10}}>
                        SPRZEDAJ
                    </Button>
                    <Button variant="outlined" color="default" style={{width: 120,}}>
                        HISTORIA
                    </Button>
                </div>
                <div style={{ display: showMe?"block":"none" }}>
                    <Calculatorbuy />
                </div>
                <div style={{ display: !showMe?"block":"none" }}>
                    <Calculatorsell />
                </div>
            </div>
            <div className="room-for-socials"></div>

import React, { useState } from 'react';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import Livebsv from './livebsv.js';



export default function Calculatorbuy() {
    const [value, setValue] = useState(0);
   
    return (
        <form className="calculator" noValidate autoComplete="off">
            <div>
                <Livebsv />
            </div>
            <div className="typebox">
                <div className="textfield">
                    <TextField error={false} id="outlined-number" label="PLN" helperText="Min. wartość 100zł"  
                    type="tel"
                    value={value}
                    InputProps={{ 
                        inputProps: { min: "100", max: "5000", step: "0.01" } 
                    }}
                    variant="outlined"
                    onKeyPress={(e) => {
                        if (!/[0-9]/.test(e.key)) {
                          e.preventDefault();
                        }
                      }}
                    onChange={(e) => setValue(e.currentTarget.value)}
                    onKeyPress={(e) => {
                        if (!/[0-9]/.test(e.key)) {
                          e.preventDefault();
                        }
                      }}
                    onBlur={(e) => {
                      if (e.currentTarget.value > 0 & e.currentTarget.value < 100 ) 
                        setValue(100);
                      else if (e.currentTarget.value > 5000) 
                        setValue(5000);
                    }}
                    />
                </div>
                <div className="textfield">
                    <TextField disabled id="outlined-disabled" value={(value).toFixed(8)} label="BSV" variant="outlined" 


解决方案

You started well by loading the result on index.js(getServerSideProps).

Then, to pass the data to Main, you have to add it as a property for the component:

<Main data={data} />

Now, as Main expects a parameter, it has to be defined in main.js:

export default function Main(props) {
    const data = props.data;
    ...
}

Then, for the Calculatorbuy component you have to do the same like on Main. Define the props and use it.

这篇关于Next.js 使用 getServerSideProps 如何将道具从页面传递到组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆