![](/img/trans.png)
[英]Is it possible to pass dynamic props, from one page to another with next.js?
[英]Next js pass JSON object from one page to another page props when navigating programmatically
我在 Next.js 项目中有两个页面,在第一个页面中,用户填写表格以创建帖子,该信息存储在 JSON object 中,因此必须看到用户的第二页预览发布,如果他/她喜欢它,则创建该帖子。
object 有点大,可以作为查询参数传递(它有大约 25 个元素),但我找不到如何将它传递给第二页道具。
给出 object 的 function 的值如下所示
async function submitHandler(event) {
event.preventDefault();
validateAndSetEmail();
validateAndSetTitle();
validateAndSetSalary();
if (isFormValidated === true) {
// this checks if the user has created another post
const finalPostData = await checkExistence(Email);
if (finalPostData["user"] === "usernot found") {
setPostData({
title: Title,
name: Name,
city: City,
email: Email,
type_index: TypeNumber,
type: Type,
region_index: regionNumber,
region: region,
category_index: categoryNumber,
category: category,
range: Range,
highlighted: highlighted,
featured: featured,
show_logo: showLogo,
show_first: showFirst,
description: Description,
price: basePrice + cardPrice,
website: Website,
logo: Logo,
application_link: applicationLink,
time_to_pin: weeksToPin,
pin: pin,
post_to_google: shareOnGoogle,
});
} else {
setPostData({
// set other values to the object
});
}
// Here I want to do something like
router.push({
pathname: "/preview/",
post: PostData,
});
}
}
第二页看起来像这样:
export default function PreviewPage(props) {
const item = props.postInfo; // <= I want item to recieve the JSON object from the other page
return (
<Fragment>
<Navbar />
<div className="flex inline mt-12 ml-24">
<Card
category={item.category}
Name={item.company}
logo={item.logo}
City={item.company_city}
Website={item.company_website}
/>
<Description
title={item.job_title}
description={item.description}
category={item.category}
region={item.region}
Type={item.type}
Link={item.link}
/>
</div>
<Footer />
</Fragment>
);
}
尝试
router.push({
pathname: "/preview/",
query: PostData,
});
export default function PreviewPage() {
const router = useRouter()
const item = router.query
感谢 knicholas 的评论,在查看了 React Context 和 Redux 之后,我设法找到了解决方案。
创建了上下文提供程序文件
我创建了 Context 里面有两件事:
一个空的 object 表示稍后将填充的 previewData
占位符 function 将成为值的设置器
import React from "react"; const PreviewContext = React.createContext({ Previewdata: {}, setPreviewData: (data) => {}, }); export default PreviewContext;
然后在 _app.js
创建一个 useState 实例来存储 previewData 并具有传递给其他页面的功能,以便在填充表单时设置值,然后使用上下文提供程序包装组件
function MyApp({ Component, pageProps }) {
const [previewData, setPreviewData] = useState({});
return (
<div className="">
<PreviewContext.Provider value={{ previewData, setPreviewData }}>
<Component {...pageProps} />
</PreviewContext.Provider>
</div>
);
}
export default MyApp;
在表单页面
我得到 function 通过使用 useContext(); 来设置 previewData 的值;
const { setJobPreviewData } = useContext(jobPreviewContext);
这样,previewData 的值在应用程序中随处可用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.