Skip to content

Instantly share code, notes, and snippets.

@ThaddeusJiang
Last active May 29, 2020 03:08
Show Gist options
  • Save ThaddeusJiang/e61a8f1dd277736e556ee236434e87f5 to your computer and use it in GitHub Desktop.
Save ThaddeusJiang/e61a8f1dd277736e556ee236434e87f5 to your computer and use it in GitHub Desktop.
React Route 可以使用 state 传参,但是当直接访问 URL 时,state 会丢失

代码

// 页面 1
<Link
  key={value}
  to={{
    pathname: `/test/{record.id}`,
    state: {
      id: record.id,
    },
  }}
>
  {value}
</Link>
// 页面 2
console.log(this.props.location.state.id)

直接访问 /test/1 时,location.state 全部丢失。 error

解决方案

当页面跳转需要传递一些参数时,使用 match.params。 例子🌰:

// route 定义
<Route path="/path/:id" component={Page2}>

// Page1 中做页面跳转
<Link to="/path/123">

// Page2 中获取参数
const { id } = this.props.match.params
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment