【问题标题】:Passing data to next screen in react-router将数据传递到 react-router 中的下一个屏幕
【发布时间】:2021-01-20 14:08:22
【问题描述】:

我想将用户名变量传递到 react-router v6 中的下一个屏幕:

// Sample 
const App = () => {

const pass = () => {
//Variable to be passed
let username = 'john.smith'
  navigate('next-screen', /*data*/)
}

return(
  <button onClick = {pass}></button>
)
}


export default App

【问题讨论】:

  • 首先,将其放入 localStorage 并在下一个屏幕中获取值。这样做会在页面刷新期间保持您的价值。
  • 你读过react-router-v6 blog吗?它概述了语法。只需添加状态对象:navigate('next-screen', { username });
  • @DrewReese 如何在下一个屏幕中访问变量?
  • 我相信和以前一样,路由道具:props.location.state.username.

标签: node.js reactjs web web-applications react-router


【解决方案1】:

navigate('next-screen', {userName});

React-router 提供了一些有用的属性,只要确保组件针对next-screen 渲染是用withRouter(component) 导出的,如果您按照这些步骤操作,那么在您的next-screen 控制台this.props.location.state.userName 中,您将拥有您的变量到下一个组件。

注意:如果您的导航与this.props.history.push 相同

如果没有,那么也将 withRouter 添加到您当前的组件中,这将使您可以访问当前组件中的history 作为道具。

【讨论】:

  • OP 正在使用 react-router-dom v6,navigation 替换 history 进行路由推送。 V6 Getting Startedv5 to v6 Migration Guide
  • 尽管如此,您仍然可以从location.state.userName 获得state
  • 如果您使用钩子,那么只需使用useLocation 并访问location.state.userName
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 2020-10-14
  • 1970-01-01
  • 2021-07-01
相关资源
最近更新 更多