我是NextJs的新手,我正尝试通过组件将对象传递给另一个页面。我将发布代码,并更好地解释我要做什么:
对象是这样的:
objectEx = {
name: 'name',
description: 'description'
}
这是主要组成部分: 我试图在Router.push
中传递对象export default class ComponentDummy extends Component {
handleSubmit = value => e => {
e.preventDefault()
Router.push({
pathname: '/OtherPage'
query: { **PASS AN OBJECT HERE** } //what im trying is: query: { objectEx: objectEx},
}
}
}
这是我试图接收查询对象的页面
const OtherPage = ({ query }) => {
return(
<div>
Do Stuff with the object here
</div>
)
}
OtherPage.getInitialProps = ({ query }) => {
return { query }
}
然后在上面的页面上尝试访问该对象,例如:
query.objectEx.name
这没有按照我的预期工作。我该如何实现?
预先感谢
答案 0 :(得分:3)
Well, first thing is you passed object as a query param.
Router.push({
pathname: '/OtherPage'
query: { data: objectEx}
}
So, in order to access the object in the OtherPage, you need to fetch this inside componentDidMount.
componentDidMount() {
let data = window.location.search;
console.log(data)
}