React Router Complicated Params No Using Query

react router complicated params

We always facing a problem when building SPA apps with react & react router between diff route paths —— list page and detail pages need to share some data:

we can just solve it with url params just in path, query, or search just like below

1
2
3
4
5
6
7
8
9
10
11
12
// path params
<Route path="querylist/:taskId" component={QueryList} />

// and we can get the params like this
const { taskId } = this.props.params

// query & search params
<Link target="_blank" to={ { pathname: '/crawler/group/duplicate/' + ${row.id}, query: { taskId: 12345 } } }>duplicate list</Link>

<Link target="_blank" to={ { pathname: '/crawler/group/duplicate/' + ${row.id}, search: querystring.stringify({ taskId: 12345 }) } }>duplicate list</Link>

const { query, search } = this.props.location

but the disadvantage is obviously:

1.the url is just ugly

2.we should concern about the character set in url, it may exist the reality that browser not support such params in url

solutions

redux solution

actually we just want a centralized state manage solution, and we can just solve it with redux. But actually I don’t like solution like this, if I suggest solution like this, there’s no this post.

2 reasons below:

1.redux can be cumbersome with some app state like fetching data, submiting data

2.there’s much template code(repeat code) using redux

so I quit redux

location state

actually react-router location support custom state passing with paths, we can just handle like this

1
2
3
4
5
this.props.router.push({ pathname: '/crawler/normalize/' + taskId,
  state: Object.assign({ taskName: '123' }, this.props.location.state) })

// and can access
const state = this.props.location.state

Just little tricks.