【问题标题】:Is it possible to pass dynamic props, from one page to another with next.js?是否可以使用 next.js 将动态道具从一个页面传递到另一个页面?
【发布时间】:2020-08-12 01:26:23
【问题描述】:

我是 Next 新手,一直在尝试制作一个页面(index.js),它获取数据(国家)然后显示该数据,其中每个返回的元素(国家)都有一个按钮可以转到页面( info.js)将显示特定国家/地区数据的位置,想知道是否可以将道具(所有国家/地区数据)传递到 info.js 页面?我已尝试阅读文档并观看 YT 视频,但似乎无法理解我在阅读/观看的内容。

index.js:

import Link from 'next/link'

Welcome.getInitialProps = async function (props) {
  const res = await fetch('https://restcountries.eu/rest/v2/all')
  const data = await res.json()
  return {
    data: data
  }
}

const MyLink = props => {
  return (
    <p>
      <Link href={`/info?name=${props.name}`} >
        <a>Learn More</a>
      </Link>
    </p>
  )
}

function Welcome(props) {
  return (
    <div>
      <div className="main-content">
        <style jsx>{`
          .main-content {
            width: 80%;
            margin: 0 auto;
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            grid-gap: 5px;
          }
          .item {
            border: 1px solid black;
            text-align: center;
          }
          .item ul{
            padding: 0;
          }
          .item ul li {
            list-style-type: none;           
          }
        `}</style>
        {props.data.map(country => (
          <div key={country.numericCode} className="item">
            <h4>{country.name}</h4>
            <p>Region: {country.region}</p>
            <p>Population: {country.population}</p>
            <MyLink name={country.name}  borders={country.borders} currencies={country.currencies}/>
          </div>
        ))}
      </div>
    </div>
  )
}

export default Welcome

info.js:

import { withRouter } from 'next/router'
import Link from 'next/link'

const Info = (props) => {
  return (
    <div>
      <h1>{props.router.query.name}</h1>
      <Link href="/">
        <a>Home</a>
      </Link>
    </div>
  )
}

export default withRouter(Info)

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    MyLink 组件中而不是使用Link,您可以创建一个普通的div(将其设置为链接的样式),然后使用nextjs router 将该div 的onClick 推送到不同的页面:

    //import useRouter
    import { useRouter } from 'next/router'
    //then call it
    const router = useRouter()
    
    
    const MyLink = props => {
      return (
        <p onClick={() => {
            router.push({
              pathname: `/info?name=${props.name}`,
              query: { data: //data to pass },
            })
          }}>
            <a>Learn More</a>
        </p>
      )
    }    
    

    您可以在query 键中的位置对象中访问该数据

    import {useLocation} from ""
    const location = useLocation()
    const data = location.query
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多