如何解决是否可以通过next.js将动态道具从一页传递到另一页?
我是Next的新手,并一直试图制作一个页面(index.js)以获取数据(国家),然后显示该数据,其中每个返回的元素(国家)都有一个转到页面的按钮( info.js)将显示特定国家/地区数据的地方,想知道是否有可能将道具(所有国家/地区数据)传递到info.js页面?我尝试阅读文档并观看YouTube视频,但似乎无法理解我在阅读/观看的内容。
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)
解决方法
在MyLink
组件中,您可以创建一个普通的div(像链接一样设置样式),而无需使用Link
,然后使用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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。