【问题标题】:Pass object to query on Router.push NextJs将对象传递给 Router.push NextJs 上的查询
【发布时间】:2020-06-13 18:29:45
【问题描述】:

我是 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

这并没有像我想象的那样工作。我怎样才能做到这一点?

提前致谢

【问题讨论】:

  • 这应该可以帮助你stackoverflow.com/a/55182740/7785337
  • 并非如此,因为在示例中他们正在传递参数并且我试图传递整个对象
  • @kivul 你找到解决方案了吗?我也是 next 的新手,但是像这样将整个对象传递给查询不会起作用:Router.push({ pathname: '/OtherPage' query: myObj }) 编辑:但是,我想它仍然不适用于嵌套字段..
  • @ZenVentzi 我没有,我只是传递了很多字段:|
  • 这个问题主要是基于意见的,请查看stackoverflow.com/help/closed-questions

标签: javascript reactjs react-router next.js


【解决方案1】:
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)
}

【讨论】:

  • 这不起作用? TS2322:类型“对象”不可分配给类型“字符串 |号码 |布尔值 |只读字符串[] |只读数字[] |只读布尔[] |空 |不明确的'。 “Object”类型缺少“readonly boolean[]”类型中的以下属性:length、concat、join、slice 等 18 个。
猜你喜欢
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
  • 2017-01-15
  • 1970-01-01
  • 2020-11-09
相关资源
最近更新 更多